简体   繁体   English

在mysql的同一张表上左联接

[英]left join on same table in mysql

I am trying to apply left join on same table but I am not getting the desired results. 我正在尝试在同一张表上应用左联接,但是没有得到期望的结果。

I have this table 我有这张桌子

Table -- Pages 表格-页数

id    name        parent        status
1     AAA         0             draft
2     BBB         1             live
3     CCC         13            live
4     DDD         0             live
5     EEE         4             live
6     FFF         4             live

I want all the rows where id status is live and their parent id's status is also live.So in the above example id 2 should not appear as it's parent id 1 status is draft. 我希望所有具有id状态的行都处于活动状态,并且其父id的状态也处于活动状态。因此在上面的示例中,不应显示id 2,因为其父id 1的状态为草稿。

I have made a sqlfiddle -- http://www.sqlfiddle.com/#!2/d6b31/4 我做了一个sqlfiddle- http ://www.sqlfiddle.com/#!2 / d6b31 /4

Any help is highly welcomed. 任何帮助都非常欢迎。 Thanks in advance. 提前致谢。

Make sure your fiddle's schema includes all cases. 确保小提琴的模式包括所有情况。 The cases you provided did not include a child not live without a parent. 您提供的案例不包括没有父母就不能生活的孩子。

This should do what you are expecting. 这应该可以完成您的期望。

SELECT a.id, a.name, a.parent, a.status
FROM pages a
LEFT JOIN pages b ON a.parent = b.id and b.status='live'
WHERE a.status='live' AND (b.status='live' OR a.parent=0)

Adjusted cases: 调整案例:

(1, 'AAA', '0', 'draft'),
(2, 'BBB', '1', 'live'),
(3, 'CCC', '13', 'live'),
(4, 'DDD', '0', 'live'),
(5, 'EEE', '4', 'live'),
(6, 'FFF', '4', 'draft'),
(7, 'GGG', '0', 'draft')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM