Designing a table in mysql - mysql

Mysql , php newbie here. Please be nice .
I have a list of colonies - colony1 , colony2,..., colony100.
Say Colony5 is nearby to colony4, colony9 and colony10.
Colony4 is nearby to colony5, colony9, colony10 and colony11 . Different colonies have different number of nearby colonies.
How do I store and fetch this data in mysql ?
Currently I am thinking a table that would look like this ->
id | colony name | nearby_colony_id_1 |nearby_colony_id_2 |nearby_colony_id_3 | nearby_colony_id_4
Is there a better way of doing this ?
I hope my question was clear.

Designing tables is fun!
If you want to store data where things are "nereby," you can do it with a graph (data structure). If you don't care about the specifics of nearby and only that a colony is nearby, you can just do this with another table. Do not do what you are trying to do (id_2, id_3, etc.) This is not a normalized DB and can lead to anomalies. A lot of people make this mistake the first time.
CREATE TABLE
Colonies (`id` int unsigned NOT NULL auto_increment, `name` varchar(255));
CREATE TABLE
Nearby_colonies (`a_id` int unsigned NOT NULL, `b_id` int unsigned NOT NULL);
So you have your colonies, in the colonies table. Then, for every nearby colony to that colony, you have an entry in Nearby_colonies that has a pair of IDs (order should not matter, but the names have to be different). This links the two colonies as Nearby colonies. Now one colony can have as many Nearby_colony entries as it likes instead of being limited to id_2, id_3, id_4, etc.
This also prevents anomalies from occurring because the relationship itself is stored for each colony, not just for one colony about another.
If you want to get even more specific and store the distance between the two colonies, no problem! Just add another field to Nearby_colonies to do that. Obviously the distance from colony a to colony b is the same in either direction ;P

i guess that you already have the answer, but it's important to understand the idea behind the solution so in the future you could do it yourself
You have a class named colonies that is related to itself (e.g "a colonie is nearby multiple colonies") in a many-to-many relationship. That's called NxN recursive relationship. in a simple UML diagram it'd be something like
now that you have the objects model, it'd be easier to create the db tables. A NxN relationship could be interpreted as an intermediary table that contains both ids as the primary key. In this case we'll need a table that i'll call tbl_nearby
witch is basically #tandu's answer, but i prefer using foreign keys because it will preserve the data integrity.
its a good idea to use UML objects model and then translate that model into database tables because that way it'd be easier for you to design really complex models
Good luck

You need two tables. The first will hold the colony specifications (id, name, ...), the second will hold links between colonies. In the first table you will have one row per colony.
Ex:
Id Name
1 colony1
2 colony2
3 colony3
4 colony4
In the second table, you will have a column for the id of the colony, a column for the id of the nearby colony. In this table, you will have one row per colony neighbour.
Ex (here colony1 has colony 2 and 3 as nearby colonies):
ColonyId NeighbourId
1 2
1 3
You can use foreign key to ensure that the colony referenced in table 2 does exist in table 1.

Related

Normalize two tables with same primary key to 3NF

I have two tables currently with the same primary key, can I have these two tables with the same primary key?
Also are all the tables in 3rd normal form
Ticket:
-------------------
Ticket_id* PK
Flight_name* FK
Names*
Price
Tax
Number_bags
Travel class:
-------------------
Ticket id * PK
Customer_5star
Customer_normal
Customer_2star
Airmiles
Lounge_discount
ticket_economy
ticket_business
ticket_first
food allowance
drink allowance
the rest of the tables in the database are below
Passengers:
Names* PK
Credit_card_number
Credit_card_issue
Ticket_id *
Address
Flight:
Flight_name* PK
Flight_date
Source_airport_id* FK
Dest_airport_id* FK
Source
Destination
Plane_id*
Airport:
Source_airport_id* PK
Dest_airport_id* PK
Source_airport_country
Dest_airport_country
Pilot:
Pilot_name* PK
Plane id* FK
Pilot_grade
Month
Hours flown
Rate
Plane:
Plane_id* PK
Pilot_name* FK
This is not meant as an answer but it became too long for a comment...
Not to sound harsh, but your model has some serious flaws and you should probably take it back to the drawing board.
Consider what would happen if a Passenger buys a second Ticket for instance. The Passenger table should not hold any reference to tickets. Maybe a passenger can have more than one credit card though? Shouldn't Credit Cards be in their own table? The same applies to Addresses.
Why does the Airport table hold information that really is about destinations (or paths/trips)? You already record trip information in the Flights table. It seems to me that the Airport table should hold information pertaining to a particular airport (like name, location?, IATA code et cetera).
Can a Pilot just be associated with one single Plane? Doesn't sound very likely. The pilot table should not hold information about planes.
And the Planes table should not hold information on pilots as a plane surely can be connected to more than one pilot.
And so on... there are most likely other issues too, but these pointers should give you something to think about.
The only tables that sort of looks ok to me are Ticket and Flight.
Re same primary key:
Yes there can be multiple tables with the same primary key. Both in principle and in good practice. We declare a primary or other unique column set to say that those columns (and supersets of them) are unique in a table. When that is the case, declare such column sets. This happens all the time.
Eg: A typical reasonable case is "subtyping"/"subtables", where entities of a kind identified by a candidate key of one table are always or sometimes also of the kind identifed by the same values in another table. (If always then the one table's candidate key values are also in the other table's. And so we would declare a foreign key from the one to the other. We would say the one table's kind of entity is a subtype of the other's.) On the other hand sometimes one table is used with attributes of both kinds and attributes inapplicable to one kind are not used. (Ie via NULL or a tag indicating kind.)
Whether you should have cases of the same primary key depends on other criteria for good design as applied to your particular situation. You need to learn design including normalization.
Eg: All keys simple and 3NF implies 5NF, so if your two tables have the same set of values as only & simple primary key in every state and they are both in 3NF then their join contains exactly the same information as they do separately. Still, maybe you would keep them separate for clarity of design, for likelihood of change or for performance based on usage. You didn't give that information.
Re normal forms:
Normal forms apply to tables. The highest normal form of a table is a property independent of any other table. (Athough you might choose that form based on what forms & tables are alternatives.)
In order to normalize or determine a table's highest normal form one needs to know (in general) all the functional dependencies in it. (For normal forms above BCNF, also join dependencies.) You didn't give them. They are determined by what the meaning of the table is (ie how to determine what rows go in it in any given situation) and the possible situtations that can arise. You didn't give them. Your expectation that we could tell you about the normal forms your tables are in without giving such information suggests that you do not understand normalization and need to educate yourself about it.
Proper design also needs this information and in general all valid states that can arise from situations that arise. Ie constraints among given tables. You didn't give them.
Having two tables with the same key goes against the idea of removing redundancy in normalization.
Excluding that, are these tables in 1NF and 2NF?
Judging by the Names field, I'd suggest that table1 is not. If multiple names can belong to one ticket, then you need a new table, most likely with a composite key of ticket_id,name.

SQL Structure for several tables

I need to create a mySQL database that keeps information about vehicles. My instincts were to create one table with as many columns as I need, but then I read about the problems in doing so. After researching, I think I'm on the right track with the following structure:
Vehicles Database
Motorcycles Table
id|road|cruising|touring|
Cars Table
id|sedan|coupe|hatchback|
Colours Table
id|green|red|blue|black|silver|white|yellow|etc..
Make Table
id|ford|chevrolet|gm|toyota|bmw|etc..
Quadrant Table (1-4)
id|motorcycle|car|truck
So basically I have a table for the objects - cars, motorcycles, trucks - and then tables for the fields/properties - Colour, Make, etc. and then a table for the Quadrant the vehicle is seen in, with a value of 1-4 where each row is an instance of only one vehicle.
The problem I'm having is understanding where the primary and foreign keys need to be in order for me to be able to organize the data:
By each individual vehicle selected along with its fields
By quadrant, showing each vehicle and their respective fields
The user counting cars should be able to input the vehicle type, the field values and the quadrant it's seen in and the db gets populated - and then I need to call the data by quadrant to analyze the data.
I don't know if or how a JOIN statement will be used? How do I go about structuring this database to suit my needs?
FWIW, dba.stackexchange says basic SQL questions belong here, so I hope I'm in the right place.
Can you tell, what is your exact need for the database i.e what functionality you need.
I suggest tables like following:
1) Vehicle table:
id|type which might contain info like 1|Motorcycle, 2|Car
2) category table:
id(foreign key)|category|color which contain info like 1|touring|Black, 2|Car|Hatchback
3) Make table: (if you need to create another table)
id (foreign key to table 1)|Make
I have not understood the functionality of quadrant table but with these 3 table you can create views according to your needs and play around with it.
From my point of view:
I will create a table CarBrands, with columns Id, BrandName, Description, which will serve as a look up.
Then I will create another table Cars with Id, CarBrandId, ColorId (From Colors Table), Description, which is your table with user records.
Same with your other entities. I suggest you search about Entity Relationship Diagrams, a good way of helping you come up with a good design.
Also look at this old StackOverflow question, this will help you.

Database design issue regarding identifying relationships and many to many relationships

I have a weird database design issue that I'm not sure if I'm doing this right or not. Since my current design is really complicated, I've simplified it in the following diagram with a comparison using houses and occupants (not my actual entities).
So, here is what part of the database design looks like:
Standard Conditions:
Multiple houses
Multiple floors per house
Multiple bedrooms per floor
Not-so-standard Conditions:
Each occupant can live in multiple houses
Each occupant can have multiple bedrooms per house
Each occupant can only have one bedroom per floor, per house (this is the tricky part) For example, they can have one bedroom on floor 1, one bedroom on floor 2 and one bedroom on floor 3, but never two bedrooms on the same floor
Thus, what I'm trying to accomplish is this. In the app design, I know the house, I know the floor and I know the occupant. What I need to find out with this information without the user specifying is what bedroom the occupant has based on those 3 criteria. There are two solutions. The first is that in the occupants_has_bedrooms table, I make the primary key the occupants_id, bedrooms_floors_id and the bedrooms_floors_houses_id. However, when I take away bedrooms_id from the primary key, the table is no longer an identifying relationship to the parent (bedrooms). It is an identifying relationship though because it couldn't exist without the parent. Therefore, something tells me I need to keep all four ids as the primary key. My second option is a unique index between those three values, however this is when I considered I may be approaching this wrong.
How do I accomplishing this?
Here's a general database design strategy that is not specific to MySQL but should still be helpful.
It's good that you know how you are going to query your data, but don't let that overly affect your model (at least at first).
The first thing to be clear on is what is the PK for each table? It looks you are using composite keys for floors and bedrooms. If you used an informationless key (ID column per table) strategy for all tables except your intersection table Occupants_has_bedrooms, it would makes your joins simpler. I'm going to assume you can, so here's how to go from there:
The first thing I would change is to get rid of floors_house_id column in bedrooms - this is now redundant and can be gotten from a join.
Next, make the following changes to occupants_has_bedrooms:
The PK for should only be two columns, occupants_id and bedroom_id. (why? Because a primary key should only contain enough info to uniquely identify a row).
Remove the bedrooms_floors_houses_id, as that's determined by bedrooms_floors_id and is not needed.
add a unique constraint on (occupants_id, bedrooms_floors_id) to enforce your "not so standard" conditions.
Finally, do an inner join with all tables except Occupants, add your three conditions in the WHERE clause. This should get you the result you want. If you really want the composite keys, you can still do it cut it gets messy. Sorry I'm not near an editor or I'd diagram it for you.
I would design the database reverse of what u did.
House
id
name
Floors -- Many to many
Floor
id
name
Bedrooms -- Many to many
optional: you can have a back pointer to house
Bedroom:
id
name
Occupants -- many to many
optional : back pointer to floor
Occupant:
id
name
optional : back pointer to Bedroom
Now having this many to many table you can query your conditions rather easily.

Representing News Post in mySQL

I'm currently working on a blog for a college news organization. Each post, though, will represent a full show, with multiple contributors and multiple titles.
For example, a post might have three news stories, each with its own title and some contributors for each:
"Story 1" by (id1) and (id2)
"Story 2" by (id3)
"Story 3" by (id4) and (id5)
So for each post, there would be an index (1, 2, 3...) for each individual story, a VARCHAR for the title, and id's that represent contributors, whose details are stored in another "contributors" table. The problem is that I don't know how many stories there will be, or how many contributors there will be per story. It could range from ~3 at the least to up to 6. In case our show expands in the future, I'd like to have the capability to scale up to even more than 6 posts, too.
I want to represent this structure concisely in a mySQL column, but I'm not sure how to do that. One solution would be to create another mySQL table to save the details for each individual story, but I'd prefer to avoid that hassle. The ideal solution would be if I could somehow create an "array" within a mySQL column, which could store (for each story) an index, a string, and multiple id's to show who the contributors are.
Is this possible, or will I have to create a new table to keep track of each story?
Don't use a column - use a table. It can be a simple InnoDB table which doesn't really hurt performance at all. Define a combined primary key (story_id, contributor_id) and insert all contributions in that table.
What you name in your question is called a M:N table. Don't ever go there - it's a very bad thing to do and is, in fact, nearly impossible in relational databases.
Save yourself some future heartburn. Create the extra table. It looks like a table of [Posts] with a one-to-many relationship to [Stories] where [Stories] has a many-to-many relationship to [Contributors].
You could store a comma-delimited string value of contributor ids or story ids in one column, but how, exactly would you relate them? What would seem to be your best bet in that case would be to make it an 'array' of 'arrays', where your main string consisted of pairs of strings strung together through commas.. I (so it's just my opinion, okay?) would avoid using unless totally necessary (can't think of one instance at this time)...
So create your relationships tables. Just to illustrate one approach to the idea:
-- a story may have multiple contributors
CREATE TABLE story_contributor_rel (
story_id INT NOT NULL
, contributor_id INT NOT NULL
)
-- a post may have multiple stories
CREATE TABLE post_story_rel (
post_id INT NOT NULL
, story_id INT NOT NULL
)
Or cheat it a bit, but I'd recommend against this also(!):
-- a less-normalized way
CREATE TABLE post_relationships (
post_id INT NOT NULL
, story_id INT NOT NULL
, contributor_id INT NOT NULL
)
These are just the simplest approaches. Naturally, you'd want to have either additional indentity columns and/or proper indexing and primary key settings, but this is just the way I can illustrate the point I'm driving at better.
Imagine this too.. If you were to put all those relationships in logical columns, then without the application it would not be so easy for anyone to understand what's going on in your tables. If you don't put any logic in the table structures and if you would properly set relationships tracking (meaning relationship tables), then it would appear transparent. One look at these tables and one would not take long enough to understand..
That's just my opinion. :) Cheers!

Database Design: Composite key vs one column primary key

A web application I am working on has encountered an unexpected 'bug' - The database of the app has two tables (among many others) called 'States' and 'Cities'.
'States' table fields:
-------------------------------------------
idStates | State | Lat | Long
-------------------------------------------
'idStates' is an auto-incrementing primary key.
'Cities' table fields:
----------------------------------------------------------
idAreaCode | idStates | City | Lat | Long
----------------------------------------------------------
'idAreaCode' is a primary key consisting of country code + area code (e.g. 91422 where 91 is the country code for india and 422 is the area code of a city in India). 'idStates' is a foreign key derived from 'States' table to associate each city in the 'Cities' table with its corresponding State.
We figured that the country code + area code combination would be unique for each city, and thus could safely be used as a primary key. Everything was working. But a location in India found an unexpected 'flaw' in the db design - India, like the US is a federal democracy and is geographically divided into many states or union territories. Both the states and union territories data is stored in the 'States' table. There is, however, one location - Chandigarh - which belongs to TWO states (Haryana and Punjab) and is also a union territory by itself.
Obviously, the current db design doesn't allow us to store more than one record of the city 'Chandigarh'.
One of the solutions suggested is to create a primary key combining the columns 'idAreaCode' and 'idStates'.
I'd like to know if this is the best solution possible?
(FYI: we are using MySQL with the InnoDB engine).
More information:
The database stores meteorological information for each city. Thus, the state and city are the starting point of each query.
Fresh data for each city is inserted everyday using a CSV file. The CSV file includes an idStates (for state) and idAreaCode (for city) column which is used to identify each record.
Database normalization is important to us.
Note: The reason for not using an auto incrementing primary key for the city table is that the database is updated everyday / hourly using a CSV file (which is generated by another app). And each record in the CSV file is identified by the idStates and idAreaCode column. Hence it is preferred that the primary key used in the city table is the same for every city, even if the table is deleted and refreshed again. Zip codes (or pin codes) and area codes (or STD codes) meet the criteria of being unique, static (don't change often) and a ready list of these are easily available. (We decided on area codes for now because India is in the process of updating its pin codes to a new format).
The solution we decided on was to handle this at the application level instead of making changes to the database design. In the database we will only be storing one record of 'Chandigarh'. In the application we've created a flag for any search for 'Chandigarh, Punjab' or 'Chandigarh, Haryana' to redirect search to this record. Yeah, it's not ideal, but an acceptable compromise since this is the ONLY exception we've come across so far.
It sounds like you are gathering data for a telephone directory. Are you? Why are states important to you? The answer to this question will probably determine which database design will work best for you.
You may think that it's obvious what a city is. It's not. It depends on what you are going to do with the data. In the US, there is this unit called MSA (Metropolitan Statistical Area). The Kansas City MSA spans both Kansas City, Kansas and Kansas City, Missouri. Whether the MSA unit makes sense or not depends on the intended use of the data.
If you used area codes in US to determine cities, you'd end up with a very different grouping than MSAs. Again, it depends on what you are going to do with the data.
In general whenever hierarchical patterns of political subdivisions break down, the most general solution is to consider the relationship many-to-many. You solve this problem the same way you solve other many-to-many problems. By creating a new table, with two foreign keys. In this case the foreign keys are IdAreacode and IdStates.
Now you can have one arecode in many states and one state spanning many area codes. It seems a shame to accpet this extra overhead to cover just one exception. Do you know whether the exception you have uncovered is just the tip of the iceberg, and there are many such exceptions?
Having a composite key could be problematic when you want to reference that table, since the referring table would have to have all columns the primary key has.
If that's the case, you might want to have a sequence primary key, and have the idAreaCode and idStates defined in a UNIQUE NOT NULL group.
I think it is best to add another table, countries. Your problem is an example why database normalization is important. You can't just mix and match different keys to one column.
So, I suggest you to create these table:
countries:
+------------+--------------+
| country_id | country_name |
+------------+--------------+
states:
+------------+----------+------------+
| country_id | state_id | state_name |
+------------+----------+------------+
cities
+------------+----------+---------+-----------+
| country_id | state_id | city_id | city_name |
+------------+----------+---------+-----------+
data
+------------+----------+---------+---------+----------+
| country_id | state_id | city_id | data_id | your_CSV |
+------------+----------+---------+---------+----------+
The bold fields are primary keys. Enter a standard country_id like 1 for US, 91 for india, and so on. city_id should also use their standard id.
You can then find anything belongs to each other pretty fast with minimal overhead. All data can then entered directly to data table, thus serving as one entry point, storing all the data into single spot. I don't know with mysql, but if your database support partitioning, you can partition data tables according to country_id or country_id+state_id to a couple of server arrays, thus it will also speed up your database performance considerably. The first, second, and third table won't take much hit on server load at all, and only serve as reference. You will mainly working on fourth data table. You can add data as much as you wish, without any duplicate ever again.
If you only have one data per city, you can omit data table and move CSV_data to cities table like this:
cities
+------------+----------+---------+-----------+----------+
| country_id | state_id | city_id | city_name | CSV_data |
+------------+----------+---------+-----------+----------+
If you go with adding an additional column to the key so that you can add an additional record for a given city, then you're not properly normalizing your data. Given that you've now discovered that a city can be a member of multiple states, I would suggest removing any reference to a state from the Cities table, then adding a StateCity table that allows you to relate states to cities (creating a m:m relationship).
Imtroduce a surrogate key. What are you going to do when area codes change numbets or get split? Using business keys as a primary key almost always is a mistake.
Your above summary is another example of why.
"We figured that the country code + area code combination would be unique for each city, and thus could safely be used as a primary key"
After having read this, I just stopped to read anything further in this topic.
How could someone figure it in this way?
Area codes, by definition (the first one I found on internet):
- "An Area code is the prefix numbers that are used to identify a geographical region based on the North American number Plan. This 3 digit number can be assigned to any number in North America, including Canada, The United States, Mexico, Latin America and the Caribbean" [1]
Putting aside that they are changeable and defined only in North America, the area codes are not 3-digits in some other countries (3-digits is simply not enough having hundred thousands of locations in some countries. BTW, my mother's area code has 5 digits) and they are not strictly linked to fixed geographical locations.
Area codes have migrating locations like arctic camps drifting with ice, normadic tribes, migrating military units or, even, big oceanic ships, etc.
Then, what about merging a few cities into one (or vice versa)?
[1]
http://www.successfuloffice.com/articles/answering-service-glossary-area-code.htm
I recommend adding a new primary key field to the Cities table that will be simply auto-incremental. The KISS methodology (keep it simple).
Any other solution is cumbersome and confusing in my opinion.
The database is not Normalised. It may be partly Normalised. You will find many more bugs and limitations in extensibility, as a result.
A hierarchy of Country then State then City is fine. You do not need a many-to-many additional table as some suggest. The said city (and many in America) is multiply in three States.
By placing CountryCode and AreaCode, concatenated, in a single column, you have broken basic database rules, not to mention added code on every access. Additionally, CountryCode is not Normalised.
The problem is that CountryCode+AreaCode is a poor choice for a key for a City. In real terms, it has very little to do with a city, it applies to huge swaths of land. If the meaning of City was changed to town (as in, your company starts collecting data for large towns), the db would break completely.
Magician has the only answer that is close to being correct, that would save you from your current limitations due to lack of Normalisation. It is not accurate to say that Magician's answer is Normalised; it is correct choice of Identifiers, which form a hierarchy in this case. But I would remove the "id" columns because they are unnecessary, 100% redundant columns, 100% redundant indices. The char() columns are fine as they are, and fine for the PK (compound keys). Remember you need an Index on the char() column anyway, to ensure it is unique.
If you had this, the Relational structure, with Relational Identifiers, your problem would not exist.
and your poor users do not have to figure silly things out or keep track of meaningless identifiers. They just state, naturally: State.Name, City.Name, ReadingType, Data ...
.
When you get to the lower end of the hierarchy (City), the compound PK has become onerous (3 x CHAR(20) ), and I wouldn't want to carry it into the Data table (esp if there are daily CSV imports and many readings or rows per city). Therefore for City only, I would add a surrogate key, as the PK.
But for the posted DDL, even as it is, without Normalising the db and using Relational Identifiers, yes, the PK of City is incorrect. It should be (idStates, idAreaCode), not the other way around. That will fix your problem.
Very bad naming by the way.