3 Table Join giving me duplicate records - mysql

I'm trying to do a 3 table join and it's giving me duplicate records so I'm unsure what I'm doing incorrectly.
SELECT e.*, cs.*, c.* FROM employee e
LEFT JOIN coffee_shop cs ON e.shop_id = cs.shop_id
LEFT JOIN coffee c ON cs.shop_id = c.shop_id
I want the coffee_shop table to join on the employee table's shop_id and the coffee table to join on coffee_shop's shop_id to perform a 3 table join. However it's giving me duplicate rows (9 rows) when all the tables only have 3 rows each.
How do I perform this join without duplicates?
Edit:
If I do only the join on the first two tables(employee and coffee_shop) it is as expected
I want to perform one more join from coffee onto coffee_shop. Which should also return 3 rows
Here is the result I want:

This will give you 3 rows for your use-case. For each shop_id in the coffee table, this will return the row with the first coffee_id.
Depending on which coffee you want to return, you can adjust the logic for the row_rank field.
SELECT e.*, cs.*, c.*
FROM employee e
LEFT JOIN coffee_shop cs ON e.shop_id = cs.shop_id
LEFT JOIN (
SELECT *,
RANK() OVER(PARTITION BY shop_id ORDER BY coffee_id) as row_rank
FROM coffee
) c ON cs.shop_id = c.shop_id and c.row_rank = 1

Try to use DISTINCT in your query like :
SELECT DISTINCT e.*, cs.*, c.* FROM employee e
LEFT JOIN coffee_shop cs ON e.shop_id = cs.shop_id
LEFT JOIN coffee c ON cs.shop_id = c.shop_id

if your main tables is employee,
SELECT e.*, cs.*, c.* FROM employee e
INNER JOIN coffee_shop cs ON e.shop_id = cs.shop_id
LEFT JOIN coffee c ON cs.shop_id = c.shop_id

Related

Combine and Display query result

I have 2 query:
SELECT CustomerID,count(b.BookingStatus) as 'NotComplete'
FROM Booking b, Customer c
WHERE c.CustomerID=b.BookingCustomerID
AND(b.BookingStatus='Pending'
OR b.BookingStatus='OTW')
GROUP BY c.CustomerID
SELECT c.CustomerID, r.*
FROM Customer c,Regular r
WHERE c.CustomerID=r.RegularCID
Result:
1st query
2nd query
How to combine these 2 result together?
also, display the zero(count) as well.
Thanks!
this is what I get after few hours of trying..obviously it's not what I want..
SELECT c.CustomerID,count(b.BookingStatus) as 'NotComplete',r.RegularID
FROM Booking b, Customer c
JOIN Regular r on r.RegularCID=c.CustomerID
WHERE c.CustomerID=b.BookingCustomerID
AND (b.BookingStatus='Pending'
or b.BookingStatus='OTW'
or b.BookingStatus='Started'
or b.BookingStatus='Unclaimed'
or b.BookingStatus='Confirmed')
GROUP by r.RegularID
You can JOIN to the Regular table and then LEFT JOIN to a derived table of counts in the Booking table. We do it this way to avoid having to GROUP BY all the columns in the Regular table:
SELECT c.CustomerID, r.*, b.NotComplete
FROM Customer c
JOIN Regular r ON r.RegularCID = c.CustomerID
LEFT JOIN (SELECT BookingCustomerID, COUNT(*) AS NotComplete
FROM Booking
WHERE BookingStatus IN ('Pending', 'OTW', 'Started', 'Unclaimed', 'Confirmed')
GROUP BY BookingCustomerID) b ON b.BookingCustomerID = c.CustomerID
Use join on regular table, and subquery on your first select
SELECT t1.*, r.RegularCID FROM (
SELECT CustomerID,count(b.BookingStatus) as 'NotComplete',
FROM Booking b
INNER JOIN Customer c ON c.CustomerID=b.BookingCustomerID
WHERE (b.BookingStatus='Pending' OR b.BookingStatus='OTW')
GROUP BY c.CustomerID) t1
LEFT JOIN Regular r on r.CustomerID = t1.CustomerID

Getting all records from INNER JOINS of multiple tables

I have three tables tblCourse , tblDegree , tblStudent. I have created a course and degree relation table as like tblCourseDegreeRelation. This relational table uses foreign keys of course and degree table as like:
The tblCourseDegreeRelation table is like:
The tblCourse table is like:
The tblDegree table is like:
The tblStudent (In this table the degree id is foreign key d_id) table is like:
I need to get all records including the tblStudent all record using this query:
SELECT * from tbldegree d
INNER JOIN tblcoursedegreerelation cdr ON d.d_id = cdr.d_id
INNER JOIN tblcourse c ON cdr.c_id = c.c_id
INNER JOIN tblstudent s ON d.d_id = s.d_id
ORDER BY cdr.cdr_id DESC
But this only returns the one student's record while I've two students in the database see below:
How I can get all students records from the joins query?
In your case you have all inner joins, so it will return results where both/all tables satisfies their criteria (on clause).
Viewing your data your student 1 => Ali has a relation with degree 1 =>BS Information Technology.
Further degree 1 has courses (1 => Programming, 2 => English, 5=> Mathematics , 6 => Electronics)
So for student 1 your inner join clause works because it has data in all joined tables.
Now if we look for your student 3 => Bilal who has a relation with degree 3 => BS Mathematics, But this degree has no assigned courses that is why your student Bilal isn't returned
To get all students no matter their related degree has courses you can turn your inner joins into left join not for all tables but for tblcoursedegreerelation and tblcourse
SELECT *
FROM tblstudent s
INNER JOIN tbldegree d ON d.d_id = s.d_id
LEFT JOIN tblcoursedegreerelation cdr ON d.d_id = cdr.d_id
LEFT JOIN tblcourse c ON cdr.c_id = c.c_id
ORDER BY cdr.cdr_id DESC
Demo
In the result set you can see following columns as null due to no association with courses
cdr_id, c_id, d_id, c_id, c_name, c_credit
Just do a Right join on tblstudent:
SELECT * from tbldegree d
INNER JOIN tblcoursedegreerelation cdr ON d.d_id = cdr.d_id
INNER JOIN tblcourse c ON cdr.c_id = c.c_id
RIGHT JOIN tblstudent s ON d.d_id = s.d_id
ORDER BY cdr.cdr_id DESC
EDIT
This way is better:
SELECT c.d_id,c.d_name,c.d_fee,cdr.cdr_id,cdr_c_id,deg.c_name,deg.d_credit,a.s_id,a.s_name
FROM tblstudent a
left join tblDegree c ON a.d_id = c.d_id
left join tblcoursedegreerelation cdr ON cdr.d_id=c.d_id
left join tblcourse deg on deg.c_id=cdr.c_id
ORDER BY cdr.cdr_id DESC

SQL join over multiple tables

With a statement like this, I can get recipe names along with how many
ingredients each one of them has.
SELECT
r.name, COUNT(i.id) as num_ingredients
FROM recipes AS r
LEFT JOIN recipe_ingredients ON r.id = recipe_ingredients.recipe_id
LEFT JOIN ingredients AS i ON recipe_ingredients.ingredient_id = i.id
GROUP BY r.id
How would I add chefs.name to my SELECT along with data that I already have?
Try this
SELECT
r.name, COUNT(i.id) as num_ingredients, che.name AS chefs_name
FROM recipes AS r
LEFT JOIN recipe_ingredients ON r.id = recipe_ingredients.recipe_id
LEFT JOIN ingredients AS i ON recipe_ingredients.ingredient_id = i.id
LEFT JOIN chefs AS che ON r.chef_id = che.id
GROUP BY r.id
If I understood, you would like to JOIN chefs table also and select its name.
You have to alias it in the SELECT statement because you select 2 columns with the same name.
I also think that the data type for column recipes.chef_id should be the same as chefs.id (both int(11) or int(255)).

Joining three tables - Mysq-l an inner and outer join perhaps?

I am struggling to get this query to work . I have three tables and I want to do a query to get the red area.
Each circle is a table with different structure. I have managed a lot of combinations of inner joins but i specially cant get all the red areas.
A Payments : idPayment , idInvoice , Amount , date.
B Invoice : idInvoice , amount date.
C PromissoryNotes: IdNote , idInvoice, amount, date.
so far ...
SELECT B.idInvoice,A.idPayment,C.idNote FROM (Invoice b INNER JOIN payments a ON a.idInvoice=b.idInvoice) LEFT OUTER JOIN PromissoryNotes c ON c.idInvoice=b.idInvoice ORDER BY idInvoice.
DOESNT QUITE WORK
Any suggestions?
You were pretty close -- another OUTER JOIN and some WHERE criteria will do the trick:
SELECT B.idInvoice, A.idPayment, C.idNote
FROM Invoice b
LEFT JOIN payments a ON a.idInvoice=b.idInvoice
LEFT JOIN PromissoryNotes c ON c.idInvoice=b.idInvoice
WHERE a.idInvoice IS NOT NULL
OR c.idInvoice IS NOT NULL
ORDER BY B.idInvoice
What this basically says is give me all results from table B, where there's a match in table a or table c.
Condensed SQL Fiddle Demo
You could do this two ways:
1) Create a set A that is the inner join of B and A, create a set C that is the inner join of B and C, then union A and C.
2) Create a sub query that inner joins A and B, then full outer join to a sub query that inner joins C and B.
Example of 1)
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
UNION
SELECT b.idInvoice FROM Invoice B
JOIN PromissoryNotes C on c.idInvoice = B.id Invoice
Example of 2)
SELECT idInvoice FROM
(
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
) B FULL OUTER JOIN
(
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
) C on b.idInvoice = C.idInvoice
Try
SELECT B.idInvoice, A.idPayment, C.idNote FROM Invoice B INNER JOIN payments A ON A.idInVoice = B.idInvoice INNER JOIN PromissoryNotes C ON C.idInvoice = B.idInvoice ORDER BY idInvoice
INNER JOIN means you get the intersection of both tables. So this is what you want.
Does this do the trick?
SELECT
ZZ.idInvoice,
ZZ.idPayment,
YY.idInvoice,
YY.idNote
FROM
(SELECT idInvoice, idPayment
FROM Invoice b
INNER JOIN payments a ON a.idInvoice=b.idInvoice) AS ZZ
FULL OUTER JOIN
(SELECT idInvoice, idNote
FROM PromissoryNotes c
INNER JOIN payments a ON a.idInvoice=c.idInvoice) AS YY ON ZZ.idInvoice = YY.idInvoice
SELECT p.idInvoice, p.idPayment, idNote
FROM Payments p JOIN Invoice i ON p.adInvoice-i.adInvoice RIGHT OUTER JOIN PromissoryNotes
UNION
SELECT i.idInvoice, idPayment, idNote
FROM Invoice i JOIN PromissoryNotes pn ON i.idInvoice=pn.idInvoice RIGHT OUTER JOIN Payments
You need to include the outer joins because the resulting tables that are to be unioned must have the same schema. I believe these are the desired fields from the query.

MySQL Join Query (possible two inner joins)

I currently have the following:
Table Town:
id
name
region
Table Supplier:
id
name
town_id
The below query returns the number of suppliers for each town:
SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t
INNER JOIN Suppliers s ON s.town_id = t.id
GROUP BY t.id, t.name
I now wish to introduce another table in to the query, Supplier_vehicles. A supplier can have many vehicles:
Table Supplier_vehicles:
id
supplier_id
vehicle_id
Now, the NumSupplier field needs to return the number of suppliers for each town that have any of the given vehicle_id (IN condition):
The following query will simply bring back the suppliers that have any of the given vehicle_id:
SELECT * FROM Supplier s, Supplier_vehicles v WHERE s.id = v.supplier_id AND v.vehicle_id IN (1, 4, 6)
I need to integrate this in to the first query so that it returns the number of suppliers that have any of the given vehicle_id.
SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t
INNER JOIN Suppliers s ON s.town_id = t.id
WHERE s.id IN (SELECT sv.supplier_id
FROM supplier_vehicles sv
WHERE sv.vehicle_id IN (1,4,6))
GROUP BY t.id, t.name
Or you could do an INNER JOIN (as your supplier join is INNER, but this will remove towns with no suppliers with those vehicles) and change the COUNT(s.id) TO COUNT(DISTINCT s.id)
If I remember correctly, you can put your second query inside the LEFT OUTER JOIN condition.
So for example, you can do something like
...
LEFT OUTER JOIN (SELECT * FROM Suppler s, Supplier_vehicles ......) s ON s.town_id=t.id
In that way you are "integrating" or combining the two queries into one. Let me know if this works.
SELECT t.name, count(s.id) as NumSupplier
FROM Town t
LEFT OUTER JOIN Suppliers s ON t.id = s.town_id
LEFT OUTER JOIN Supplier_vehicles v ON s.id = v.supplier_id
WHERE v.vehicle_id IN (1,4,6)
GROUP BY t.name