querying primary keys from a foreign key - mysql

I'm fairly new to MySQL and I am struggling querying or referencing primary key's by foreign keys specified in a table. Can someone please explain how to do this in fairly simple terms, as everything I've searched is a bit hard to understand considering majority of others have allot more MySQL knowledge then me.
Let's just assume these are the tables:
CREATE TABLE IF NOT EXISTS customer(
custID int AUTO_INCREMENT,
custLname varchar(30),
custAdd varchar(100),
custSuburb varchar(30),
custPcode varchar(4),
custState varChar(20),
custPhone varchar(10),
PRIMARY KEY (custID)
)ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS tour(
DailyTourID int,
tourDate DATE,
tourTime TIME,
tourName varchar(30),
tourDriverID int,
tourBusID varchar(2),
PRIMARY KEY (DailyTourID, tourDate),
) ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS TourCustLink(
TourCustLinkID int AUTO_INCREMENT,
TourID int,
TourDate DATE,
customerID int,
PRIMARY KEY (TourCustLinkID),
FOREIGN KEY (TourID, TourDate) REFERENCES tour(DailyTourID, tourDate),
FOREIGN KEY (customerID) REFERENCES customer(custID)
) ENGINE = INNODB;
I am aware this is a pretty bad example, but lets say I want to show the custLname, custAdd, custPhone and tourDates for each customer. How would I accomplish this?

JOIN them:
SELECT
c.custLname,
c.custAdd,
c.custPhone,
t.TourDate,
t.TourName,
...
FROM TourCustLink AS tl
INNER JOIN Customer AS c ON tl.customerId = c.custID
INNER JOIN Tour AS t ON tl.tourID = t.DailyTourID
AND tl.tourDate = t.tourDate;
You might also need to use OUTER JOINs (LEFT JOIN or RIGHT JOIN) instead of INNER JOIN, in case you want to include those unmatched rows.
For more information about the JOIN types see this article:
A Visual Explanation of SQL Joins

Related

Extending a database by adding a table with new information, here is what I have, whats the issue?

I have to extend a database by adding a table with information I will add later in the SQL, the exact question is: "You need to extend the movie database by creating a new table with the following schema: award", below is the SQL I came up with but doesn't seem to work, any help?
CREATE TABLE Awards (
Award varchar(50) NOTNULL,
Year INT NOTNULL,
Category varchar(50) NOTNULL,
movie_id varchar(3),
star_id varchar(3),
FOREIGN KEY (movie_id) REFERENCES Awards(movie.movie_id),
FOREIGN KEY (star_id) REFERENCES Awards(star.star_id)
);
If any info is missing to get help, let me know and I can provide it to make it easier, thanks!
The foreign keys should have the name of the foreign table before the parenthesus and the name of the foreign column inside the parenthesis. There shouldn't be a .
CREATE TABLE Awards (
Award varchar(50) NOTNULL,
Year INT NOTNULL,
Category varchar(50) NOTNULL,
movie_id varchar(3),
star_id varchar(3),
FOREIGN KEY (movie_id) REFERENCES movie(movie_id),
FOREIGN KEY (star_id) REFERENCES star(star_id)
);

Simple attendance list SQL schema architecture advice

I have a sport club presence list on paper which I have to bring online.
Basically, I have everything in handle except the SQL schema architecture.
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
If the person is present we make a x with a pen on paper :)
To do to look the same like on the paper but in an app I try to develop a Java Vaadin App with Spring Data JPA-Hibernate.
On paper and in the future APP look like this:
And this is the MySQL schema:
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table isPresent(
id int PRIMARY KEY AUTO_INCREMENT,
isPresent boolean
);
create table persons_isPresent(
person_id int,
isPresent_id int,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
isPresent_id int,
training_time datetime,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
It seems unnecessary to have ispresent ID's.
I would keep your Person table as is.
Create a Training table with an ID and time, and an TrainingAttendance table with a Training ID and a Person ID. If you want to check a person's attendance at a training, check if a record exists in TrainingAttendance with the Person's ID and the Training ID.
CREATE TABLE PERSON (
PERSON_ID INTEGER NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(20) NOT NULL);
CREATE TABLE TRAINING (
TRAINING_ID INTEGER NOT NULL PRIMARY KEY
TRAINING_TIME DATETIME NOT NULL);
CREATE TABLE TRAINING_ATTENDANCE (
TRAINING_ID INTEGER NOT NULL,
PERSON_ID INTEGER NOT NULL,
FOREIGN KEY(PERSON_ID) REFERENCES PERSON(PERSON_ID),
FOREIGN KEY(TRAINING_ID) REFERENCES TRAINING(TRAINING_ID),
PRIMARY KEY(TRAINING_ID, PERSON_ID));
I think it might be cleaner to think about training sessions independently. Then you could achieve that with three tables [training]<-[attendee]->[person], where the attendee is a binding table. So maybe something like this:
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
training_time datetime
);
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table attendee(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
training_id int,
FOREIGN KEY (person_id) REFERENCES person(id),
FOREIGN KEY (training_id) REFERENCES training(id)
);
I tried it out with some simple inserts/select and it might do the trick for you?
insert INTO person (first_name) VALUES ('Pavel');
insert INTO training (training_time) VALUES (NOW());
insert INTO attendee (person_id, training_id) VALUES (1,1);
select person.first_name, training.training_time
from attendee, person, training
where person.id = attendee.person_id
AND training.id = attendee.training_id;

MySQL: How do I get to a column of another table via a mapping table

I am trying to create a database for assignments where there is a table for the tasks, a table for the persons and a table for the assignment of a person to a task.
Now I have tried to access the task table with a select statement and at the same time get all assigned persons but nothing worked. (because a task is also assigned to other tables)
Is there a way or do I have to use several statements for this?
This is how i created my Tables:
CREATE TABLE Locations (ID INT AUTO_INCREMENT, LocationID VARCHAR(255),
PRIMARY KEY (ID));
CREATE TABLE Persons (ID INT AUTO_INCREMENT, FirstName VARCHAR(255), LastName
VARCHAR(255), PRIMARY KEY (ID));
CREATE TABLE Tasks (ID INT AUTO_INCREMENT , TaskName VARCHAR(255), LocationID
INT, PRIMARY KEY (ID),
FOREIGN KEY (LocationID) REFERENCES Locations(ID));
CREATE TABLE Assinment (TaskID INT, PersonID INT,
PRIMARY KEY (TaskID, PersonID), FOREIGN KEY (TaskID)
REFERENCES Tasks(ID), FOREIGN KEY (PersonID)
REFERENCES Persons(ID));
And this is the UML.
I do not want my joins on the Assinment table like
SELECT (FirstName, LastName, TaskName) FROM ((Assinment INNER JOIN Tasks ON
Assinment.TaskID = Tasks.ID) INNER JOIN Persons ON Assinment.PersonID =
Persons.ID)
because the tasks table has more joins (e.g. locations and priorities) so i want my query start with
SELECT (ID, TaskName, FirstName, LastName, LocationName) FROM Tasks [...]
so i can get all data by id of the task
The Output then should give me this table.
Thanks for help :)
EDIT
Ouput added and desired input is now more specified
You can try subqueries :
SELECT column-names
FROM table-name1
WHERE value IN (SELECT column-name
FROM table-name2
WHERE condition)

MySQL Query returning duplicated results

Fairly new to mySQL . Trying to get a query to work, but keep getting the right results, but duplicated.
Here's the query
SELECT DISTINCT
band.band_name, concert.venue_name
FROM
band, concert
WHERE
concert.date="2012-10-17" AND band_name
IN
(SELECT band.band_name FROM band WHERE band.band_id
IN
(SELECT tour.band_id from tour where tour.tour_name
IN
(SELECT tour_name from concert where concert.date="2012-10-17")));
DDL:
CREATE TABLE band (
band_id INT,
band_name VARCHAR(50),
genre VARCHAR(20),
PRIMARY KEY (band_id) );
CREATE TABLE musician (
person_id INT,
name VARCHAR(50),
band_id INT,
PRIMARY KEY (person_id),
FOREIGN KEY (band_id) REFERENCES band(band_id) );
CREATE TABLE tour(
tour_name VARCHAR(50),
band_id INT,
PRIMARY KEY (tour_name),
FOREIGN KEY (band_id) REFERENCES band(band_id) );
CREATE TABLE venue(
venue_name VARCHAR(30),
hire_cost INT,
PRIMARY KEY (venue_name) );
CREATE TABLE concert(
concert_id INT,
date DATE,
tour_name VARCHAR(50),
venue_name VARCHAR(30),
ticket_sales INT,
PRIMARY KEY (concert_id),
FOREIGN KEY (tour_name) REFERENCES tour(tour_name),
FOREIGN KEY (venue_name) REFERENCES venue(venue_name) );
I'm totally lost. Any help would be greatly appreciated.
Joining tables is the way to go, you do not pile all your conditions into the where clause:
SELECT DISTINCT
b.band_name, c.venue_name
FROM concert c
join venue v on v.venue_name = c.venue_name -- thats how those 2 tables connect
join tour t on t.tour_name = c.tour_name -- thats how those 2 tables connect
join band b on b.band_id = t.band_id -- thats how those 2 tables connect
WHERE c.date="2012-10-17" -- and this gives you all the bandnames and
-- venuenames that play on every concert on this date
This way the DB can optimize your query and due to the joins on the tables does not need to scan so much data.

MySQL: How do you set the "master" row of a self reference table?

How do you specify the first row?
Is set FOREIGN_KEY_CHECKS = 0 the best idea?
How do you handle inconsistency of this approach?
CREATE TABLE people (
id INT PRIMARY KEY,
parent_id INT NOT NULL,
FOREIGN KEY (id) REFERENCES people (id)
) ENGINE = INNODB;
I believe you are looking for this:
CREATE TABLE people (
id INT PRIMARY KEY,
parent_id INT,
FOREIGN KEY (parent_id) REFERENCES people(id)
);
NULL is a typical way to express that something has no parent -- which is presumably what you mean by "master".