簡體   English   中英

在條件上執行多個左連接並獲得非空列值

[英]Do Multiple Left Join on condition and get non null column value

我有一個表格,其中包含網站上發布的最新評論,並且我想根據評論類型加入其他表格。

注釋表類似於此結構:

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  |

謝謝。

由於您永遠都不會從NewsTutorial中獲得相同comment you might go with的日期,因此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返回日期。

嘗試這個:

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)

您也可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM