I have two different tables and I am not sure of the best way to get it out of the first normal form and into the second normal form. The first table hold the user information while the second is the products associated with the account. If I do it this way, I know it is only in the NF1 and that the foreign key of User_ID will be repeated many times in Table 2. See the tables below.
Table 1
|User_ID (primary)| Name | Address | Email | Username | Password |
Table 2
| Product_ID (Primary Key) | User_ID (Foreign Key) |
Is this a better way to make table two in which the user ID is not repeated? I have thought about having a separate table in the database for each user, but from all of the other questions I read on StackOverFlow, this is not a good idea.
The constraints I am working with are 1-1000 users and Table Two will have approximately 1-1000 indexes per user. Is there a better way to create this set of tables?
I don't see NF2 violated. It states:
a table is in 2NF if it is in 1NF and no non-prime attribute is dependent on any proper subset of any candidate key of the table.
quoted from Wikipedia article "Second normal form", 2016-11-26
Table 2 has only one candidate key, the primary key. The primary key consists of only one column. So, there is no proper subset of a candidate key. So, NF2 can't be violated unless NF1 is not fulfilled.
you says "to make table two in which the user ID is not repeated"
then why you dont do
Table 1
|User_ID (primary)| Name | Address | Email | Username | Password | Product_ID ( Foreign Key nullable)|
Table 2
| Product_ID (Primary Key)|
There's nothing wrong with a value appearing many times. Redundancy arises when two queries that aren't syntactically equivalent always both return the same value. Only uncontrolled redundancy is bad. Normalization controls some redundancy by replacing a table by smaller ones that join to it.
Normalization decomposes a table independently of other tables. (We define the normal form of a database as the lowest normal form that all of its tables are in.) Foreign keys have nothing to do with violating normal forms.
Learn what it means for a table to be in a given normal form. You will need to learn a definition. And the definitions of the terms it uses. And the definitions of the terms they use. Etc. A table is in 2NF when every non-prime column has a functional dependency that is full on every candidate key. Also learn the algorithm for decomposing a table into components that are in a given normal form. Assuming that these tables can hold more than one row, so that {} is not a candidate key, both these tables are in 2NF.
A table in 2NF is also in 1NF. So you don't want "to get it out of the first normal form".
2NF is unimportant. When dealing with functional dependencies, what matters is BCNF, which decomposes as much as possible but requires certain higher-cost contraints, and 3NF, which doesn't decompose as much as possble but requires certain lower-cost constraints.
Related
This is my table :
| ID |
| xxx0000 |
| xxx0001 |
| xxx0002 |
i want to make my id pattern like that, but i dont know how to generate it?
You have two different pieces of data, so make two different columns.
ID INT NOT NULL AUTO_INCREMENT,
SomethingElse SomeOtherType NOT NULL
What SomethingElse is named and what data type it is would be up to you. xxx doesn't tell us much.
If both of these things combined make up your primary key, you can use a composite key of multiple columns:
PRIMARY KEY (SomethingElse, ID)
The same integrity checks for any primary key will continue to apply, the database will simply check both columns for combined uniqueness.
At this point you have the data you want, now it's just a matter of displaying it how you want. Whether you do that in SQL or in PHP is up to you. Whether you want the application to see them as a single value or see the underlying different values, also up to you.
Selecting them as a single value from SQL could be simple enough. Something like:
SELECT CONCAT(SomethingElse, ID) AS ID FROM ...
If you always want those padded zeroes then this question will help. Other string manipulations you might want to do would also be tackled one at a time (and each could result in its own Stack Overflow question if you need assistance with it).
But the basic idea here is that what you have is a composite value. In a relational database you would generally store the underlying values and perform the composition when querying the data.
I am wondering what is the best solutions to store relations between 2 tables in mysql.
I have following structure
Table: categories
id | name | etc...
_______________________________
1 | Graphic cards | ...
2 | Processors | ...
3 | Hard Drives | ...
Table: properties_of_categories
id | name
_____________________
1 | Capacity
2 | GPU Speed
3 | Memory size
4 | Clock rate
5 | Cache
Now I need them to have connections, and question is what is a better, more efficient and lighter solution, which is important because there may be hundreds of categories and thousands of properties assigned to them.
Should I just create another table with a structure like
categoryId | propertyId
Or perhaps add another column to categories table and store properties in text field like 1,7,19,23
Or maybe create json files named for example 7.json with content like
{1,7,19,23}
As this question is pertaining to Relational World, I would suggest to add another table to store many to many relationship between Category and Property.
You can also use JSON column to store many values in one of the table.
JSON Datatype is introduced in MYSQL 5.7 and it comes with various features for JSON data retrieval and updation. However if you are using older version, you would need to manage it with string column with some cumbersome queries for string manipulation.
The required structure depends on the relationship type: one-to-many, many-to-one, or many-to-many (M2M).
For a one-to-many, a foreign key (FK) on the 'many' side relates many items to the 'one' side. The reverse is correct for many-to-one.
For many-to-many (M2M) you need an intermediate relational (or junction) table exactly as you suggest. This allows you to "reuse" both categories and properties in any combinations. However it's slightly more SQL - requiring 2 JOINs.
If you are looking for performance, then using FKs to primary keys (PKs) would be very efficient and the queries are pretty simple. Using JSON would presumably require you to parse in PHP and construct on-the-fly second queries which would multiply your coding work and testing, data transfer, CPU overhead, and limit scalability.
In your case I'm guessing that both "graphics cards" and "hard drives" could have e.g. "memory size" plus other properties, so you would need a M2M relational table as you suggest.
As long as your keys are indexed (which PKs are), your JOIN to this relational table will be very quick and efficient.
If you use CONSTRAINTs with your relations, they you ensure you maintain data integrity: you cannot delete a category to which a property is "attached". This is a good feature in the long run.
Hundreds and thousands of records is a tiny amount for MySQL. You would use this technique even with millions of records. So there's no worry about size.
RDBMS databases are designed specifically to do this, so I would recommend using the native features than try to do it yourself in JSON. (unless I'm missing some new JSON MySQL feature! *)
* Since posting this, I indeed stumbled across a new JSON MySQL feature. It seems, from a quick read, you could implement all sorts of new structures and relations using JSON and virtual column keys, possibly removing the need for junction tables. This will probably blur the line between MySQL as an RDBMS and NoSQL.
The first solution is better when it comes to relational databases. You should create a table that will pair each category to multiple properties (1:n relationship)
You could structure the table like so:
CREATE TABLE categories_properties_match(
categoryId INTEGER NOT NULL,
propertyId INTEGER NOT NULL,
PRIMARY KEY(categoryId, propertyId),
FOREIGN KEY(categoryId) REFERENCES categories(id) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY(propertyId) REFERENCES properties_of_categories(id) ON UPDATE CASCADE ON DELETE CASCADE
);
The primary key ensures that there will be no duplicate entries, that means entries that match one category to the same property twice
I'm not sure if a "sub-table" is the proper term for it, so let me explain a bit better.
I'm setting up a website which contains multiple items, now I've created 2 separate tables in my MySQL database: general and platforms.
My goal now is to split the data of each item into these 2 tables, which works fine so far, but my problem now is the following:
The platforms table has the following structure:
ID
Name
URL
I want to keep track of each item by their ID, so the ID for item #1 should be equal in all tables.
Now, if I have say 3 different platforms for item #1, I'll add every element in the platforms table, but their ID's don't match.
And if I have multiple items, each with multiple platforms it will start to look really messy.
Is it possible to have a table that looks like this?
ID
Name
URL
Hopefully the images clarify it more, basically; I want to have a table that groups together multiple elements.
Is this possible or would I have to do it by assigning a secondary non auto-incrementing ID to each item and manually group the platforms together in PHP?
Looks like you have a one-to-many relationship. Generically, that means
a row in general can be related to zero, one or more rows in platforms.
a row in platforms is related to exactly one row in general.
To implement this design, store the id value from the general table as a foreign key in the platforms table.
id
general_id -- foreign key references id in general table
name
url
Rows in the two tables are related by virtue of a common value.
id general_id name url
--- ---------- --------- --------------------------
77 1 Platform1 http://item1.com/platform1
78 1 Platform2 http://item1.com/platform2
79 1 Platform3 http://item1.com/platform3
To have the database enforce referential integrity, you would need to use a storage engine that supports that (e.g. InnoDB), and you can declare a constraint
ALTER TABLE `platforms` ADD
`general_id` INT NOT NULL COMMENT 'fk ref general.id' AFTER `id`;
(The datatype of the general_id columns must exactly match the datatype of the id column in the general table.)
Before you can enforce the constraint, the values in the new general_id column will have to match a value in the referenced column.
To define the constraint:
ALTER TABLE `platforms`
ADD CONSTRAINT FK_platforms_general
FOREIGN KEY (`general_id`) REFERENCES `general`(`id`)
i am going to design my blacklist and favorite in php list which user can blacklist and favorite other persons and now i just want to know is it better to design like this
+-----+------+------------+
| uid(pk) | name | family |
+-----+------+------------+
and another table like this which is composite primary key
+-----+------+------------------------+
| uid(pk) | blacklisted_person_id(pk) |
+-----+------+------------------------+
or desgin with primary key and foreign key in it, which i dont know how to design in this case that user cant blacklist himself or blacklist some person 2 times.if someonce can describe it a little ill be grateful.
thanks in advance
Your solution is good, but I'd recommend just calling your PK in your user table just id not uid and then in your mapping blacklist table refer to it as user_id (if user is the name of the user table) and blacklisted_user_id. That way there is no ambiguity to what table these individual columns are foreign keys to.
The reason it's a good solution is that it will prevent duplicates from being entered without having to create an additional unique composite key.
I think your use of the terminology in the title is confusing and it doesn't correspond to what you are describing later in the question.
Always use artificial keys and try to avoid using natural keys. It's a good practice as you can almost never know what piece of data will have to be changed later which may affect your natural key.
| uid(pk) | name | family |
The above design is a good start.
Place as little restrictions on the data model as possible without sacrificing the data consistency.
In which case the composite key of UID, black_listed_ID can be a little too restrictive and the reason for that is that later on you may decide to keep the log of who black listed whom at different times, then your composite key design breaks.
Just use simple one to many relationship for now, describing the preferences of one user on multiple-records.
For example, the data model for user actions that can include blacklisting, whitelisting, and more can be like so:
UID, AFFECTED_USER_ID, ACTION_ID, ACTION_DT
where ACTION_ID is FK to an "ACTION lookup table" describing black-listing, white_listing, grey listing, etc, etc.
You can also have the table describing the current state of affairs, but that current state can also be calculated or retrieved from the above data.
I have these tables:
category table:
cat_id (PK)
cat_name
category_options table:
option_id (PK)
cat_id (FK)
option_name
option_values table:
value_id (PK)
option_id (FK)
value
classifieds table:
ad_id (PK) (VARCHAR) something like "Bmw330ci_28238239832"
poster_id (FK)
cat_id (FK)
headline
description
price
etc....
posters table:
poster_id (PK)
name
email
tel
password
etc....
Three main questions:
1- Is the above good enough? It covers all my needs atleast...
2- Sometimes when I try out different queries, I get strange results... Could you write a PHP query string which will fetch one complete ad from an ad_id only? (imagine the only variable you have is ad_id)
3- In the query string, must I specify all different tables which are connected in order to display an ad? Can't I just use something like "SELECT * FROM classifieds WHERE ad_id=$ad_id" and it would handle the links automatically, ie fetch all related information also?
Thanks and if you need more input let me know!
You have serious design problems. Never ever ever use name as a PK; it is not unique and it is subject to change! Women change thier names when they get married for instance. In fact, don't use any varchars as PKS at all. Use surrogate keys instead. Surrogate keys don't change, text keys values often do and they are slower too.
And never store name as just one field, this is a poor practice. At a minumum you need first name, last name, middle name, and suffix. You wil also need a autoincrementing id field so that John Smith at one address in Chicago can exist in the table with a different John Smith who lives elsewhere in Chicago.
No you can't get all the data from related tables without adding them to the query through the use of a join. This is database 101 and if you don't know that, then you don't understand relational databases enough to design one. Do some research into joins and querying. You can get all the information for an ad from just having the ad id though as your current relations appear to work.
Do not use implied joins when you add the other tables to your queries. They are outdated by 18 years. Learn correctly by using explicit joins.
1) If it meets your needs, then wouldn't that make it "good enough"? But seriously, I would agree with davek that you should make the ad_id field an int/bigint, and I'd also suggest the same for the posters table. Make the name a regular value field and create an autonum int/bigint PK field for it. If for any reason that user wants to change their name (for privacy concerns, perhaps), then you would have to update any foreign keys in the database as well. With an autonum key, you wouldn't have this problem.
2) Yes, from what I see you should be able to gather all the data on an ad by knowing only the ad_id.
3) No, you need to do more than that, either equi-join in a SELECT query, or use the JOIN keyword to pull your data in. MySQL doesn't have a "meta" relationship model (like MS Access), so it won't automatically understand your primary/foreign key relationships.