说
Table A Table AB Table B
+----+---------+ +-----+-----+ +----+-----+
| id | name | | ida | idb | | id | age |
+----+---------+ +-----+-----+ +----+-----+
| 1 | 'one' | | 1 | 3 | | 3 | 3 |
+----+---------+ +-----+-----+ +----+-----+
| 2 | 'two' | | 2 | 4 | | 5 | 5 |
+----+---------+ +-----+-----+ +----+-----+
| 3 | 'three' | | 2 | 5 |
+----+---------+ +-----+-----+
What I want What I get
+---------+------+ +---------+------+
| name | age | | name | age |
+---------+------+ +---------+------+
| 'one' | 3 | | 'one' | 3 |
+---------+------+ +---------+------+
| 'two' | 5 | | 'two' | 5 |
+---------+------+ +---------+------+
| 'three' | NULL | | 'two' | NULL |
+---------+------+ +---------+------+
| 'three' | NULL |
+---------+------+
我的sql是
SELECT A.name, B.age
FROM A
LEFT JOIN AB
ON A.id = AB.ida
LEFT JOIN B
ON AB.idb = B.id
约束:出于特定原因,我不想使用Where
语句,出于性能原因,我也不想使用sub-queries
。
有没有办法我只能获取关系AB匹配仅使用JOIN
/ ON
并且没有子查询存在的内容的记录?
答案 0 :(得分:2)
使用分组。
SELECT A.name, Max(B.age)
FROM A
LEFT JOIN AB
ON A.id = AB.ida
LEFT JOIN B
ON AB.idb = B.id
GROUP BY a.id, a.Name
order by a.id
或者你可以使用正确的连接。
select a.name, b.age
from
b
inner join ab on b.id = ab.idb
right join a on ab.ida = a.id
答案 1 :(得分:2)
使用表B
:
SELECT A.name, B.age
FROM A LEFT JOIN (
AB JOIN B ON AB.idb = B.id
) ON A.id = AB.ida
在sqlfiddle上查看。