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
Related
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
Now, the rule that we'd planned for the UID (Unique Membership Num/ Customer Num) to be auto-generated each time a user registers (account is created).
The rule we'd set:
FirstName LastName = FL+ 001
(the number associated with those two letters in chronological order of account creation)ie both letters are unique and only when both are repeated, should the number count go up.
eg:
John Doe - JD001
John Denver - JD002
Jane Foster - JF001
Bob Bilkins - BB001
Bill Graham - BG001
Assuming your users table would be:
create table users (
user_id int unsigned auto_increment primary key,
fname varchar(50) not null,
lname varchar(50) not null,
uid varchar(50) unique
);
Create another table, which will hold last sequence numbers for all user initials:
create table uid_seq (
initials varchar(2) not null primary key,
seq int unsigned not null
);
Then write an insert trigger for the users table, which will increment the sequence number for the given initials and return it back to generate the UID:
delimiter //
create trigger users_before_insert before insert on users
for each row begin
set #initials = concat(left(new.fname,1), left(new.lname, 1));
insert into uid_seq (initials, seq)
values (#initials, last_insert_id(1))
on duplicate key update seq = last_insert_id(seq + 1);
set new.uid = concat(#initials, lpad(last_insert_id(), 3, 0));
end //
delimiter ;
This method is concurrency safe, because we use INSERT .. ON DUPLICATE KEY UPDATE .. and return the generated value using LAST_INSERT_ID(). This way two users will never get the same UID. In worst case you might burn a sequence number, when the server crashes while processing the insert. However - If you execute your insert in a transaction, that shouldn't happen too.
Note that you still need an AUTO_INCREMENT ID, because this is the only way to find out, which row you have just inserted, unless you have a natural identifying key.
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 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'
I have to develop a table that would contain distance between destinations and need some assistance for that. I am right now almost blank on how to start
here the table show distance from point A to A, B, C AND D ARE 0, 4, 8, AND 12 respectively and so on.
need to transform this data in MySQL table to be managed by admin panel and used at client site depending on from and to destination.
Regards
In case you don't have "real" date (like geolocation) you will need to store the data in 2 tables.
First table, locations (so store A,B,C,D there, and other relevant information about the location)
Second table, 3 columns. from_location, to_location, distance. (with a key on from/to_location so it is unique. But always check for the other way around before inserting, as you can support A,C and C,A in your table)
This way you can easily extract the correct data from the database.
For example, getting the distance from A to C (SELECT distance FROM distance_table WHERE from_location = "A" AND to_location = "C")
So basically you need a table that has 3 columns. Point A, Point B, distance
In your program, you can do 2 for loop to get through the 2 dimension table as inserts.
If you want it to be unique, then in your code, you make want to try if you currently looking at B to A, check if A to B already exist before inserting again. Might be wise to also place some constraint on the table where PointA and PointB Must be unique
Make a table
Create table `table_name`( `Distance_from` varchar(2), `A` int,`B` int, `C` int, `D` int ,primary key(Distance_from));
Then insert your record like
Insert into `table_name`(`Distance_from`,`A`,`B`,`C`,`D`) values('A',0,4,8,12)
similarly insert all your rows.
I'm very new to databases and I have a quick question.
How would I design my MySQL database if I have these fields:
ID,
lat,
long,
date - multiple dates,
time - multiple times
I know I should put it into two tables, right? And how would those two tables look?
Thanks!
Your first table might be called "location" and it would have an "id" column as its primary key, along with two columns called "latitude" and "longditude" (which could be varchar or a numeric type, depending what your application requires). Your second table might be called "location_event" and it could have an "id" column as its primary key, along with a foreign key column called "location_id" that is a reference to the primary key of the "location" table. This "location_event" table would also have a "date" column and a "time" column (of types date and time respectively).
It's hard to tell what you're trying to do from the terse description but third normal form dictates that any column should be dependent on:
the key.
the whole key.
nothing but the key.
To that end, I'd say my initial analysis would generate:
Location
LocId primary key
Lat
Long
Events
LocId foreign key Location(LocId)
Date
Time
This is based on my (possibly flawed) analysis that you want to store a location at which zero or more events can happen.
It's good practice to put the events in a separate table since the alternative is to have arrays of columns which is never a good idea.
As far as I can guess the date en time are couple always appearing together. In that case I would suggest two tables, location and time.
CREATE TABLE location (
id INT NOT NULL,
lat FLOAT NOT NULL,
long FLOAT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE time (
id INT NOT NULL,
locationid INT NOT NULL,
date DATE NOT NULL,
time DATE NOT NULL
)
Optionally you can add a foreign key constraint
ALTER TABLE time ADD CONSTRAINT location_fk_constraint FOREIGN KEY location_fk_constraint (locationid)
REFERENCES location (id)
ON DELETE CASCADE
ON UPDATE CASCADE;
OK, let's say, for the sake of argument, that you are talking about longitude and latitude. That these are entries in some kind of list (perhaps a sea log? Arrgh, me maties!) of longitude and latitude. And that each of these long/lat pairs may appear more than once in the list.
Perhaps you want to build a database that figures out how many appearances each long/lat pair has, and when each appearance happened?
So how's this: First we have a table of the long/lat pairs, and we'll give each of those an ID.
ID long lat
-- ----- -----
1 11111 22222
2 33333 44444
3 55555 66666
Next, we'll have another table, which will assign each appearance of the long/lat pairs a date/time:
ID date time
-- ---- -----
1 1/1/1900 12:30
1 2/2/1900 12:31
1 3/2/1900 12:30
2 1/1/1930 08:21
Let's say you'll call the first table "longlat" and the second one "appearances".
You could find all the appearances of a single long/lat pair by doing something like:
SELECT date,time FROM appearances
LEFT JOIN longlat ON appearances.ID=longlat.ID
WHERE longlat.long = 11111 AND longlat.lat = 22222
You could count how many times something happened at a longitude of 11111, by doing:
SELECT count(ID) FROM appearances
LEFT JOIN longlat ON appearances.ID=longlat.ID
WHERE longlat.long = 11111
Hope that helps! I gotta admit, it's really quite annoying to try and guess what people mean... Try making yourself more clear in the future, and you'll see that the help you'll get will be that much more useful, concise and targeted at what you need.
Good luck!