Regarding SQL query 'join' function - mysql

I have created the following table but have troubles getting the desired output using the join function. I would like to know that if we have to select car name, price and driver name for cars made in any random year e.g.,vintage = 1995. Any help will be appreciated
create table car
(car_ID NUMBER ,
car_Name CHAR ,
car_Vintage NUMBER,
car_Price NUMBER,
PRIMARY KEY (car_ID));
create TABLE driver
(driver_ID NUMBER,
driver_Name CHAR,
PRIMARY KEY (driver_ID));
create table cardriver
(car_ID NUMBER(3) NOT NULL,
driver_ID NUMBER(4) NOT NULL,
PRIMARY KEY (car_ID,driver_ID),
FOREIGN KEY (car_ID) REFERENCES car(car_ID)
ON DELETE CASCADE,
FOREIGN KEY (driver_ID) REFERENCES driver(driver_ID)
ON DELETE CASCADE);

SELECT
c.car_Name,
c.car_Price,
d.driver_Name
FROM
cardriver as cd
INNER JOIN
car as c on c.car_ID = cd.car_ID
INNER JOIN
driver as d on d.driver_ID = cd.driver_ID
WHERE
c.car_Vintage = #Year
This assumes every car has a driver. Otherwise select from car and left join to cardriver.

Related

MySQL Query - search for person who has all B

I am trying to solve an SQL question about below question in MySQL
output the patient name who has taken treatment from all doctors at least once.
I am stuck with the "all doctors".
Is there a way to get this result with one query?
Where I have the table,
CREATE table patient (
pno VARCHAR(5) PRIMARY KEY,
name VARCHAR(15) NOT NULL,
);
CREATE table doctor (
dno VARCHAR(5) PRIMARY KEY,
name VARCHAR(15) NOT NULL,
);
CREATE table record (
id INT auto_increment PRIMARY KEY,
dno VARCHAR(5),
pno VARCHAR(5),
FOREIGN KEY(dno) REFERENCES doctor(dno)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY(pno) REFERENCES patient(pno)
ON UPDATE CASCADE
ON DELETE CASCADE
);
pno is the patient number, which is referenced by record,
dno is the doctor's number, which is referenced by record.
I think IN and EXSISTS doen't work in this situation.
Maybe using count(*) would work but, I tried using subquery below, and couldn't solve this.
SELECT count(*)
FROM doctor;
You can:
first select the cardinality of the doctors,
then select all patients whose distinct count of doctors is equal to the cardinality of doctors
hence get the patients' names.
The query should look like this:
SELECT p.name
FROM patient p
WHERE p.pno IN (
SELECT r.pno
FROM record r
GROUP BY r.pno
HAVING COUNT(DISTINCT r.dno) = (
SELECT COUNT(*)
FROM doctors
)
)
Note: I'll leave an SQL fiddle link here in case of question update with some sample data.

SQL issue with multiple foreign

Issue:
I'm using PostgreSQL Database.
I have one table (Albums) to be linked to two other tables (Clients, Domains). So if you are Client or Domain you can have Album. But in Albums table owner can handle only single foreign key. How can I solve this issue?
Dream: Single Album can own only (1) Client or Domain. Need fix issue with foreign keys. Albums: id | owner (multiple foreign -> Clients:id or Domains:id) --> can not do this | name. I just need some smart rework.
Tables (now can have Album only Domain):
Albums
Clients
Domains
Albums (table with foreign key yet):
id | owner (foreign key -> Domains:id) | name
Clients:
id | first_name | last_name
Domains:
id | owner | name
Add 2 FK columns, and a CHECK constraint, to enforce only one of them is NOT NULL...
Something like this:
CREATE TABLE albums (
id serial PRIMARY KEY,
client_id integer,
domain_id integer,
name varchar(255) NOT NULL,
FOREIGN KEY (client_id) REFERENCES clients(id),
FOREIGN KEY (domain_id) REFERENCES domains(id),
CHECK ((client_id IS NULL) <> (domain_id IS NULL))
);
To query you can use something like this:
SELECT a.id, COALESCE(c.id, d.id) AS owner_id, COALESCE(c.name, d.name) AS owner_name,
a.name AS title
FROM albums a
LEFT JOIN clients c ON a.client_id = c.id
LEFT JOIN domains d ON a.domain_id = d.id
#e_i_pi's version
CREATE TABLE entities (
id serial PRIMARY KEY,
type integer, -- could be any other type
-- any other "common" values
);
CREATE TABLE client_entities (
id integer PRIMARY KEY, -- at INSERT this comes from table `entities`
name varchar(255) NOT NULL,
);
CREATE TABLE domain_entities (
id integer PRIMARY KEY, -- at INSERT this comes from table `entities`
name varchar(255) NOT NULL,
);
CREATE TABLE albums (
id serial PRIMARY KEY,
owner_id integer FOREIGN KEY REFERENCES entities(id), -- maybe NOT NULL?
name varchar(255) NOT NULL,
);
Query:
SELECT a.id, owner_id, COALESCE(c.name, d.name) AS owner_name, a.name AS title
FROM albums a
LEFT JOIN entities e ON a.owner_id = e.id
LEFT JOIN client_entities c ON e.id = c.id AND e.type = 1 -- depending on the type of `type`
LEFT JOIN domain_entities d ON e.id = d.id AND e.type = 2
Righto, so as suggested in the comment to the answer by #UsagiMiyamoto, there is a way to do this that allows declaration of entity types, with cascading. Note that this solution doesn't support unlimited entity types, as we need to maintain concrete FK constraints. There is a way to do this with unlimited entity types, but involves triggers and quite a bit of nastiness.
Here's the easy to understand solution:
-- Start with a test schema
DROP SCHEMA IF EXISTS "entityExample" CASCADE;
CREATE SCHEMA IF NOT EXISTS "entityExample";
SET SEARCH_PATH TO "entityExample";
-- We'll need this to enforce constraints
CREATE OR REPLACE FUNCTION is_entity_type(text, text) returns boolean as $$
SELECT TRUE WHERE $1 = $2
;
$$ language sql;
-- Unique entity types
CREATE TABLE "entityTypes" (
name TEXT NOT NULL,
CONSTRAINT "entityTypes_ukey" UNIQUE ("name")
);
-- Our client entities
CREATE TABLE clients (
id integer PRIMARY KEY,
name TEXT NOT NULL
);
-- Our domain entities
CREATE TABLE domains (
id integer PRIMARY KEY,
name TEXT NOT NULL
);
-- Our overaching entities table, which maintains FK constraints against clients and domains
CREATE TABLE entities (
id serial PRIMARY KEY,
"entityType" TEXT NOT NULL,
"clientID" INTEGER CHECK (is_entity_type("entityType", 'client')),
"domainID" INTEGER CHECK (is_entity_type("entityType", 'domain')),
CONSTRAINT "entities_entityType" FOREIGN KEY ("entityType") REFERENCES "entityTypes" (name) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "entities_clientID" FOREIGN KEY ("clientID") REFERENCES "clients" (id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "entities_domainID" FOREIGN KEY ("domainID") REFERENCES "domains" (id) ON DELETE CASCADE ON UPDATE CASCADE
);
-- Our albums table, which now can have one owner, but of a dynam ic entity type
CREATE TABLE albums (
id serial PRIMARY KEY,
"ownerEntityID" integer,
name TEXT NOT NULL,
CONSTRAINT "albums_ownerEntityID" FOREIGN KEY ("ownerEntityID") REFERENCES "entities"("id")
);
-- Put the entity type in
INSERT INTO "entityTypes" ("name") VALUES ('client'), ('domain');
-- Enter our clients and domains
INSERT INTO clients VALUES (1, 'clientA'), (2, 'clientB');
INSERT INTO domains VALUES (50, 'domainA');
-- Make sure the clients and domains are registered as entities
INSERT INTO entities ("entityType", "clientID")
SELECT
'client',
"clients".id
FROM "clients"
ON CONFLICT DO NOTHING
;
INSERT INTO entities ("entityType", "domainID")
SELECT
'domain',
"domains".id
FROM "domains"
ON CONFLICT DO NOTHING
;
If you don't like the idea of inserting twice (once in client, once in entites, for example) you can have a trigger on inserts in the clients table, or alternately create an insert function that inserts to both tables at once.

SQL Getting Specific Column other than just the foreign key

I have sql table called Games as follows:
CREATE TABLE Games
(date date NOT NULL,
ho_t_id varchar(9) NOT NULL,
v_t_id varchar(9) NOT NULL,
h_score int,
v_score int,
PRIMARY KEY(date, ho_t_id, v_t_id),
FOREIGN KEY(ho_t_id) REFERENCES Team ON UPDATE CASCADE,
FOREIGN KEY(v_t_id) REFERENCES Team);
As you can see, it has two foreign keys to a table called Team. The ho_t_id and v_t_id reference to the primary key of the Team table called t_id.
I would like to show all the columns of the Games table (*) but replace the ho_t_id by the name of the team which exist in the Team table. (The Team table contains a column named Name).
How can I do that?
SELECT G.*, T1.NAME as T1_NAME, T2.NAME AS T2_NAME
FROM GAMES G
INNER JOIN TEAM T1 ON T1.T_ID=G.HO_T_ID
INNER JOIN TEAM T2 ON T2.T_ID=G.V_T_ID
You mean this?:
select t.Name, g.allOtherColumns
from Games g
inner join (
select Name, ID
from Team
) t
ON t.ID = g.v_t_id
--where ....

mysql select query from multiple tables returns duplicate results

If this question is a little vague just let me know and I will provide more info.
I have written a query that gets data from multiple tables but it isn't working how I expected it too and I am completely stumped.
Here is my code:
SELECT students.student_fname, students.student_lname
FROM students, enrolments
WHERE enrolments.courseID = 'C001';
but this just returns all of the students first and last names in the students table and these names are displayed twice.
Here is the code for the two tables:
CREATE TABLE students
(
studentID CHAR(10) NOT NULL,
student_fname VARCHAR(15) NOT NULL,
student_lname VARCHAR(15) NOT NULL,
DOB VARCHAR(10) NOT NULL,
CONSTRAINT pk_students PRIMARY KEY (studentID)
);
CREATE TABLE enrolments
(
enrolmentNo int NOT NULL AUTO_INCREMENT,
studentID CHAR(10) NOT NULL,
courseID CHAR(4) NOT NULL,
CONSTRAINT pk_enrolments PRIMARY KEY (enrolmentno),
FOREIGN KEY (studentID) REFERENCES students (studentID),
FOREIGN KEY (courseID) REFERENCES courses (courseID)
)ENGINE = INNODB;
This is because you've not defined how students relate to enrolments.
You either need to use an inner join or add a where clause that show how they relate.
For example:
FROM Students
INNER JOIN enrolments on Students.ID = enrolments.studentID
Or
FROM students, enrolements
WHERE enrolments.studentID = students.ID
The first method is newer and preferred by many; but the legacy method is also supported.
To gain a better understanding of table joins take a look at this most excellent article: http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
Otherwise you get what is called a Cartesian product of the two tables all data relates to all data.
If you do not have a unique index on enrolements (a student can only have 1 class enrolment) then a select Distinct field names or where... group by fields will also limit your results to close to what you're looking for as well.
============================ in response to follow-up comment===================
SELECT S.student_fname, S.student_lname
FROM students S
INNER JOIN enrolments E
ON S.StudentID = E.StudentID
WHERE e.courseID = 'C001'
GROUP BY S.Student_Fname, S.Student_lname
ORDER BY S.Student_LName, S.Student_FName
The group by eliminates duplicates for the same course.
The "ON statement tells the database how students relates to enrolments.
The order by is just to provide a reasonable order to results.
You cannot fetch data from two tables in this way. You have to join tables.

Mysql foreign key

I want to make a link between a table customer and a table product by an IdProduct.
Example:
Create table customer(
idcustomer INT not null,
name Varchar(20),
idproduct INT,
);
create table Product(
idproduct INT not null,
nameProduct varchar(40)
);
How can I link the two together like the foreign key system for, when I select a customer, I can get all his products? It's a question about the structure of the database.
You want to introduce a 3rd table to resolve the many-to-many relationship between customers and products. It should consist of idcustomer and idproduct.
Then, to get all the products for a given customer:
SELECT c.name, p.nameProduct
FROM Customer c
INNER JOIN CustomerProductXref cpx
ON c.idcustomer = cpx.idcustomer
INNER JOIN product p
ON cpx.idproduct = p.idproduct
WHERE c.idcustomer = 12345
In mysql a foreign key is a special type of constraint. It is preferably created with the table, but can also be added afterwards. In this case, you might define the constraint as:
ALTER TABLE customer
ADD FOREIGN KEY (idproduct)
REFERENCES Product (idproduct);
(Note that you have to use the InnoDB engine to take advantage of FK's in mysql. More here
However FK's aren't required to make a JOIN, which is how you would link the tables in a SELECT -
select c.idcustomer, c.name, p.nameproduct
from customer c
join Product p on p.idproduct=c.idproduct;
Here's how you'd make a foreign key constraint (ignoring the cardinality issues that Joe rightly suggests):
CREATE table Product(
idproduct INT not null,
nameProduct varchar(40),
PRIMARY KEY (idproduct )
);
CREATE table customer(
idcustomer INT not null,
name Varchar(20),
idproduct INT,
FOREIGN KEY (idproduct) REFERENCES Product(idproduct )
);
Get your data like this:
SELECT * FROM Product AS P
INNER JOIN Customer AS C ON C.idproduct = P.idproduct
WHERE C.idcustomer = 1