从多个表中选择使用in语句并显示所有内容,无论结果如何

时间:2018-04-05 10:58:15

标签: mysql join

我有3张桌子。

第一个表"项目"是这样的:

id  |   title
28  |   pr28
31  |   pr31
65  |   pr65
74  |   pr74

第二个表"阶段"是这样的:

pr_id   |   id  |   t_id|   title   |   comments
28      |   65  |   1   |   st1     |   bla
28      |   86  |   3   |   st3     |   blaaaa
31      |   132 |   1   |   st1     |   blabla
65      |   189 |   1   |   st1     |   bli
65      |   190 |   2   |   st2     |   blibli
65      |   224 |   3   |   st3     |   bliblib
74      |   319 |   3   |   st3     |   blibli
74      |   333 |   5   |   st5     |   blibli

第三个表" stad_ids"是这样的:

id  |   title
1   |   st1
2   |   st2
3   |   st3
4   |   st4
5   |   st5

我想从第一个表中找到t_ids为1或2的项目。这里没问题:

 SELECT a.id, st.t_id, st.title, st.comments
 FROM  `stages` AS st
 JOIN `projects` AS a ON a.id = st.pr_id
 and a.id IN (SELECT a.id FROM stages as st
 JOIN `projects` AS a ON a.id = st.pr_id
 AND st.t_id in (1,2))
 order by a.id

输出:

id  |   t_id    |   title   |   comments
28  |   1       |   st1     |   bla
31  |   1       |   st1     |   blabla
65  |   1       |   st1     |   bli
65  |   2       |   st2     |   blibli

现在,我想显示项目中有id或3的阶段,其中t_id为1或2。

SELECT a.id, st.t_id, st.title, st.comments FROM  `stages` AS st JOIN
`projects` AS a ON a.id = st.pr_id and st.t_id in (2,3) and a.id IN
(SELECT a.id FROM stages as st JOIN `projects` AS a ON a.id = st.pr_id
AND st.t_id in (1,2))
order by a.id

输出:

id  |   t_id    |   title   |   comments
28  |   3       |   st3     |   blaaaa
65  |   2       |   st2     |   blibli
65  |   3       |   st3     |   bliblib

相反,我希望得到以下输出:

id  |   t_id    |   title   |   comments
28  |   2       |   st2     |   "NO VALUE"
28  |   3       |   st3     |   blaaaa
65  |   2       |   st2     |   blibli
65  |   3       |   st3     |   bliblib

我试图使用第三张表格:

SELECT distinct a.id, ids.id AS t_id, ids.title, st.comments
FROM  `stages` AS st
JOIN `stad_ids` AS ids ON ids.id in (2,3)
JOIN `projects` AS a ON a.id = st.pr_id
and st.t_id in (2,3)
and a.id IN (SELECT a.id FROM stages as st
JOIN `projects` AS a ON a.id = st.pr_id
AND st.t_id in (1,2)) 
order by a.id

但输出会重复评论。

id  |   t_id    |   title   |   comments
28  |   2       |   st2     |   blaaaa
28  |   3       |   st3     |   blaaaa
65  |   2       |   st2     |   blibli
65  |   3       |   st3     |   bliblib

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

找到目标项目并使用2行阶段ID(2和3)进行交叉连接,以创建项目ID,阶段ID /标题的每种可能组合。使用左连接来引入注释。

SELECT a.id, ids.id as t_id, ids.title, COALESCE(st.comments, '"NO VALUE"') as comments
FROM `stad_ids` as ids
CROSS JOIN `projects` as a
LEFT JOIN `stages` as st ON ids.id = st.t_id and a.id = st.pr_id
WHERE ids.id in (2, 3) AND
      a.id IN
    (SELECT a.id FROM stages as st JOIN `projects` AS a ON a.id = st.pr_id
         AND st.t_id in (1,2)) AND
      EXISTS (SELECT 1 FROM `stages` as st1 WHERE st1.pr_id = a.id AND st1.t_id in (2, 3))
ORDER BY a.id,  ids.id;

Demo