Reputation: 6645
I'm trying to LEFT JOIN two tables, to get a list of all rows from TABLE_1 and ONE related row from TABLE_2. I have tried LEFT JOIN and GROUP BY c_id, however I wan't the related row from TABLE_2 to be sorted by isHeadOffice DESC.
Here are some sample tables
TABLE 1
c_id Name
----------------
1 USA
2 Canada
3 England
4 France
5 Spain
TABLE2
o_id c_id Office isHeadOffice
------------------------------------------------
1 1 New York 1
2 1 Washington 0
3 1 Boston 0
4 2 Toronto 0
5 3 London 0
6 3 Manchester 1
7 4 Paris 1
8 4 Lyon 0
So what I am trying to get from this would be something like:
RESULTS
c_id Name Office
----------------------------
1 USA New York
2 Canada Toronto
3 England Manchester
4 France Paris
5 Spain NULL
I'm using PHP & MySQL. Any ideas?
Upvotes: 4
Views: 382
Reputation: 18013
Why not:
SELECT c_id, name,
(SELECT t2.office
FROM table2 t2
WHERE t2.c_id = t1.c_id AND t2.isHeadOffice = 1
LIMIT 1) office
FROM table1 t1
ORDER BY 3 DESC
Upvotes: 0
Reputation: 425341
SELECT *
FROM table1 t1
LEFT JOIN
table2
ON o.id =
(
SELECT o_id
FROM table2 t2
WHERE t2.c_id = t1.c_id
ORDER BY
t2.c_id DESC, t2.isHeadOffice DESC, t2.o_id DESC
LIMIT 1
)
Create an index on table2 (c_id, isHeadOffice, o_id)
for this to work fast.
The ORDER BY
clause in the subquery may seem redundant but it is required for MySQL
to pick the right index.
Upvotes: 4
Reputation: 102478
This assumes that your isHeadOffice is a bit field and you will only have one head office per country.
SELECT
Table1.c_id,
Table1.Name,
Table2.Office
FROM
Table1
LEFT OUTER JOIN
Table2
ON
Table1.c_id = Table2.c_id
AND
Table2.isHeadOffice = 1
Upvotes: 0