在条件上执行多个左连接并获取非空列值

时间:2016-09-02 07:01:04

标签: mysql sql join left-join

我有一个包含网站上发布的最后评论的表格,我想根据评论类型加入另一个表格。

评论表与此结构类似:

id | type | ressource_id |
---+------+--------------+
1  |  1   |      10      |
2  |  3   |       7      |
3  |  3   |      12      |
4  |  1   |      22      |
5  |  4   |      22      |
6  |  5   |      23      |

新闻表:

news_id | notes|     date     |
--------+------+--------------+
10      |      |  2015-08-12  |
22      |      |  2015-07-12  |

教程表:

tuto_id | notes|     date     |
--------+------+--------------+
7       |      |  2015-06-15  |
12      |      |  2015-05-14  |

...类型表= 4,5,6

现在为了获得具体的评论,我正在两个表上进行左连接。

SELECT co.*
  FROM Comments co
       LEFT JOIN News n 
              ON co.id = n.news_id AND co.type = 1
       LEFT JOIN Tutorial t
              ON co.id = t.tuto_id AND co.type = 3
 WHERE (co.type IN (1,3)) 

我有兴趣从左表中获取日期。如何在输出列表中包含该列。

所需结果:(加入表的日期)

id | type | ressource_id |     date     |
---+------+--------------+--------------+
1  |  1   |      10      |  2015-08-12  |
2  |  3   |       7      |  2015-06-15  |
3  |  3   |      12      |  2015-05-14  |
4  |  1   |      22      |  2015-07-12  |

感谢。

3 个答案:

答案 0 :(得分:1)

由于您永远不会从NewsTutorial获取同一comment you might go with COALESCE'的日期:

SELECT co.*, COALESCE(n.date,t.date)
  FROM Comments co
       LEFT JOIN News n 
              ON co.id = n.news_id AND co.type = 1
       LEFT JOIN Tutorial t
              ON co.id = t.tuto_id AND co.type = 3
 WHERE (co.type IN (1,3))

COALESCE将返回不是null的第一个参数,因此如果有匹配的新闻,它将从News返回日期,如果没有匹配的新闻但匹配教程它将从Tutorial返回日期。

答案 1 :(得分:0)

试试这个:

SELECT co.*,coalesce(n.date,t.date)
  FROM Comments co
       LEFT JOIN News n 
              ON co.id = n.news_id AND co.type = 1
       LEFT JOIN Tutorial t
              ON co.id = t.tuto_id AND co.type = 3
 WHERE (co.type IN (1,3))
 and (co.id = n.news_id or co.id = t.tuto_id)

答案 2 :(得分:0)

您也可以使用UNION运算符。

(SELECT co.*,n.date as [date]
  FROM Comments co
       LEFT JOIN News n 
              ON co.id = n.news_id AND co.type = 1)
UNION ALL
    (SELECT co.*,t.date
      FROM Comments co
       LEFT JOIN Tutorial t
              ON co.id = t.tuto_id AND co.type = 3)
ORDER BY ID