![](/img/trans.png)
[英]MySQL two-table INNER JOIN , LEFT JOINED onto third table with only one row with lowest value
[英]Using LEFT JOIN to only selection one joined row
我正在尝试LEFT JOIN两个表,以获取TABLE_1中所有行的列表以及TABLE_2中的一个相关行。 我尝试过LEFT JOIN和GROUP BY c_id,但是我不希望TABLE_2中的相关行按isHeadOffice DESC排序。
以下是一些示例表
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
所以我想从中得到的东西就像:
RESULTS
c_id Name Office
----------------------------
1 USA New York
2 Canada Toronto
3 England Manchester
4 France Paris
5 Spain NULL
我正在使用PHP和MySQL。 有任何想法吗?
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
)
在table2 (c_id, isHeadOffice, o_id)
上创建一个索引,以便快速工作。
子查询中的ORDER BY
子句可能看起来多余,但MySQL
需要选择正确的索引。
为什么不:
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
这假设您的isHeadOffice是一个位字段,每个国家/地区只有一个总部。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.