Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am making a table of a products like different types of vehicles: cars, trucks etc. They are made by an array of countries and each country has an array of makers, like Japan has Toyota, Honda, etc and US has Ford, GM etc. Once the database is built, I need to do operations like "select all vehicles made by Toyota".
What is the best way to store that?
The data structure is not necessarily the same as your array structure. The key word is "normalisation": design your tables in a way that avoids redundancies and make sure that each record in a table contains exactly the information that is relevant to describe the subject of that particular table.
A possible structure could be:
create table vehicles(
vid int auto_increment primary key,
void int,
vname nvarchar(32),
vtype int,
vmotor varchar(32), ...)
create table oem (
oid int auto_increment primary key,
oname nvarchar(32),
countryid int, ... )
The column void of table vehicles references the primary key oid of the oem (original equipment manufacturers) table.
A typical query can be the following:
select * from vehicles where
exists (select 1 from oem where oid=void and countryid=7)
countryid is just an integer key referencing yet another table (not listed here) containing country names etc.. Assuming that record 7 of the country table contains 'Japan' then the above query will list all vehicles made in Japan.
Or - coming back to your original example -
select * from vehicles where
exists (select 1 from oem where oid=void and oname='Toyota')
would list all vehicles of that particular manufacturer.
This little example is just the starting point for you to understand `normalisation'. Like Marc B already said: Study the concept for yourself and you will be able to answer your question yourself. Here is another example based link that might be helpful: http://db.grussell.org/section008.html .
Why not just have a table called Automobiles,
and then rows like Car, Model, Company,Country
and then you can just
SELECT * FROM Automobiles WHERE Company = 'Toyota' AND Country = 'Japan'
Related
Background:
I want to create a table for storing the questions and user answer in survey for research purpose.
The questions are multiple choices but only one answer can be selected.
The questions can be added or hided by users.
The questions are the same for every user.
Also, NO interviewer information is required to store because it is anonymous.
There is no absolute answer for the question because the choices are static for every question.
Table
Survey
-id(PKey)
-submittedDate
Question
-id(PKey)
-questionText
Answer
-id(PKey)
-answerText
Access Pattern
1.Find a survey with certain id with its questions and answers.
2.Calculate the distribution of the answer for certain questions, e.g. 50% people select answer a, 25% people select answer b for question 1.
Example
1 2 3 4 5
1. How much water do you drink today ✓
2. How many apples do you eat today ✓
My question
I have a rough design of the table and some fields, but I want to get some insight of how to relating these tables, and how should I design the schema using these 3 tables.
Update
Seems the Survey Table has been misunderstood.
Here is more concrete example.
Survey id 123
1 2 3 4 5
1. How much water do you drink today(questionId 1) ✓
2. How many apples do you eat today(questionId 2) ✓
Survey id 124
1 2 3 4 5
1. How much water do you drink today(questionId 1) ✓
2. How many oranges do you eat today(questionId 3) ✓
questionId 1 belongs to Survey id 123 and 124.
Survey id 123 have questionId 1 and 2.
So it is N-to-M relationship?
CREATE TABLE Surveys (
sid ... AUTO_INCREMENT,
other info about the survey (date, who took it, etc)
PRIMARY KEY(sid),
maybe other indexes
) ENGINE=InnoDB;
CREATE TABLE S_Q (
-- no AUTO_INCREMENT needed
sid ..., -- not AUTO_INCREMENT
qid ..., -- not AUTO_INCREMENT
answer VARCHAR(...), -- the actual answer (no need to normalization)
PRIMARY KEY(sid, qid),
INDEX(qid, sid)
) ENGINE=InnoDB;
CREATE TABLE Questions (
qid ... AUTO_INCREMENT,
question_text TEXT,
PRIMARY KEY(qid)
) ENGINE=InnoDB;
// This table may be unnecessary:
CREATE TABLE Answers (
-- no AUTO_INCREMENT needed
qid ...,
answer VARCHAR(...),
answer_description TEXT,
PRIMARY KEY(qid, answer)
) ENGINE=InnoDB;
(All columns should probably be NOT NULL.)
answer is the actual answer. It is short enough and self-descriptive enough not to need a lookup via an id.
you need to add to FKs on the question table which Survey it belongs to and on the Answer table for which Question this answer.
Survey
id(PKey)
submittedDate
Question
id(PKey)
questionText
Survey_id(FK)
Answer
id(PKey)
answerText
Question_id (FK)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I’m currently trying to design my table structures for a made up database. The database will have three separate tables and track the populations of cities for 10 years. After every year, population figures will be added for each city in the database. Here is how I’ve laid out my three tables so far:
Cities (city_id, city_name, city_abbrv)
Year (year_id, year)
Stats (year_id, city_id, population)
I’m worried about not having a unique identifier in my Stats table. With 10 cities, the year data will be the same for 10 entries. Once I enter multiple years of data, the city_id will be reused. In my research on this site I’ve read that having a unique ID for every table is not required but the book I’m using to learn database design (while brief) never mentions that this is okay. I would like to know the best way to design a database that receivers data entries for the same group of things on a daily/weekly/monthly/yearly schedule. Should I add in a unique_id column to my Stats table? Or would this be a wasted column? Thanks for the help!
First of all you need each of those tables to have the column id as primary key.
A primary key is used to uniquely identify a table row. A primary key cannot be NULL since NULL is not a value. So basically those columns will be unique yes.
Question: Why you need primary keys in your tables?
Answer:
If you are looking to select data from different tables you are opting for join so you need keys to use for that join.
If you want your
table to be clustered, you need some kind of a primary key.
Side Note: You may need to get familiar with indexing columns, see advantages of indexing.
Cities (id, city_name, city_abbrv) //with id as primary key
Year (id, year) //with id as primary key
Stats (id, year_id, city_id, population) //with id as primary key
//And year_id and city_id as foregin key connected by their respective ids
If you are still beginner with MYSQL see the W3school tutorial for SQL primary keys.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm a newbie.. not sure if this is the right place to post this, so please forgive me if it isn't.. i wanted to find out how or what would be the best approach when it comes to making a table for contacts in a database.. Here is what i have :
I have a table for users, this table contains user info like usernames and passwords,etc.. i want to make a program that will allow these users to add contacts,now i don't want to create a contacts table for each user,i would like to have a contacts table which contains all contacts and be able to reference them using an id .. Help please
You have a table of users and a table of contacts:
User - UserID, Username, Pw... etc.
Contacts - ContactID, name, phone, info...etc.
For a user to have multiple contacts and for multiple users to have the same contact, you need to create a bridge table to handle the many to many relationship. In this table you'll reference the primary keys (the UserID, and ContactID) from the tables above.
UserContacts - UserID, ContactID. (this can be a composite primary key)
You need to have a table with name of your choice..let's say Contacts
You can have this structure
ContactId (Primary Key)
ContactName
UserId
Etc..
You can start with above structure and improvise..
I recommend this article..
http://www.datanamic.com/support/lt-dez005-introduction-db-modeling.html
Table creation sample code:
CREATE TABLE contact(
contact_id VARCHAR(20),
contact_name VARCHAR(20),
user_id VARCHAR(20),
password VARCHAR(20)
);
data insertion sample code:
INSERT INTO contact(contact_id,contact_name,user_id,password)
VALUES("A123","Daniel","dan2015","password");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have made a railway database with fare in it now I want to retrieve value or cost of like destination a to b - how? Please help me retrieve and how to make the tables I want it for my project? I don't want codes only help to make it.
Since I don't see your sample data, but based on your comment alone, I would do something like...
select
r.cost
from
YourRailFairTable r
where
( r.fro = 'from destination'
AND r.t = 'to destination' )
OR ( r.t = 'from destination'
AND r.fro = 'to destination' )
Since I don't know how your table is organized, I have an OR in the where clause. Because someone could go From "City A" to "City B" or From "City B" to "City A". Therefore, we can never assume that it will always be in a specific from/to order unless you somehow forced the data to have the destinations in alpha order. This way it gets in EITHER case. Just make sure you have an index on your table for both (fro, t)
FEEDBACK PER COMMENT
Not dealing with such a system of from/to type of ticketing system, I would do the following. Create one table of all possible destinations and have an auto-increment ID column. Have another table of all routes and rates. The bigger problem that really requires more effort is something I can not directly answer... Such as in air travel, a person might want to go from city A to city B, but the airline has no direct flight and needs to go from A to city X to city B. You have nothing that links them together so you would need additional logic to handle that. But for rail travel it may not be that complex, even if there are switching trains at certain stations.
CREATE TABLE Destination (
DestinationID INT NOT NULL AUTO_INCREMENT,
Destination CHAR(30) NOT NULL,
PRIMARY KEY (DestinationID),
INDEX Destination (Destination) );
then your values would be something like
DestinationID Destination
1 City A
2 City B
3 City ...Z
Next, your rates table which has an ID to both from/to destination and the rate. In this case, any insertions I would FORCE the first destination to the lower "ID" value, so even if a destination name is spelled incorrectly and adjusted, the internal ID wont.
CREATE TABLE RailRates (
RailRateID INT NOT NULL AUTO_INCREMENT,
DestFrom INT,
DestTo INT,
Rate DECIMAL(7,2),
PRIMARY KEY (RailRateID),
FOREIGN KEY (DestFrom) REFERENCES Destination ( DestinationID )
ON DELETE CASCADE,
FOREIGN KEY (DestTo) REFERENCES Destination ( DestinationID )
ON DELETE CASCADE,
INDEX FromTo( DestFrom, DestTo) );
Sample Data for rates table
RailRateID DestFrom DestTo Rate
1 1 2 123.45
2 1 3 145.67
3 1 9 287.42
4 1 14 321.93
5 2 3 46.82
6 2 9 187.18
7 etc...
Then, you would prompt a user for from/to locations, get their IDs and put them in low/high order as it would not matter which from/to and update the query something like
select
r.Rate
from
RailRates r
where
r.FromDest = lowIDNumberOfOneLocation
AND r.ToDest = highIDNumberOfOtherLocation
So I have a HTML form where users can answer single-choice questions either by checkboxing one of the three preset responses, or writing a custom answer of their own.
While this is obviously a many-to-many relationship, I still cannot find a proper way to design database tables so as to handle both types (TEXT and BOOLEAN). My current quick-and-dirty solution is to hard-code a specific choice_id in the junction table for custom answers. I'm looking for a better pattern for this.
Have the following tables:
Table 1:Question
QuestionID (ID)
QuestionText (Text)
Table 2: Question Response
QuestionResponseId (ID)
QuestionResponseTypeId (References Question Response Type)
QuestionResponseDetailsId (References Question Response Details) - This should be used for text only values (Custom Answers)
QuestionResponse (Boolean)
Table 3: Question Response Type
QuestionResponseTypeId (Id)
Description (Text) -- Dictates if the answer is a boolean or a text field
Table 4: Question Response Details
QuestionResponseDetailsId (Id)
Description (Text) - Holds the text answer to the questions
When the following tables are populated you will have a structure that holds the question, the response of the question (text or boolean).
You could then filter on this to see only text based answers, for example:
SELECT * FROM QuestionResponse
INNER JOIN QuestionResponseDetails ON QuestionResponse.QuestionResponseDetailsId = QuestionResponseDetails.QuestionResponseDetailsId
WHERE QuestionResponse.QuestionResponseTypeId = 1
Where 1 is a Text based answer and 2 is a Boolean based answer (From the Question Response Type Table)
If I were you, I would do something like this:
Table Answers:
question_id INT(11)
answer_id INT(11)
preset_answer TINYINT(1) //1, 2, 3 for three answers
custom_answer VARCHAR(255)