Query

查詢數據有問題

  • January 12, 2021

我在從表中檢索數據時遇到困難。

貝婁是我陷入困境的場景。

TableA

TableB

TableC

TableAjoins With TableBby TableA_Idcolumn,唯一的區別是如果沒有TableAid 的引用,那麼我們應該返回帶有TableA_Id = 0from的行TableB

Required Output

SELECT t1.name,
      COALESCE(t2.tag, t3.tag) tag,
      t4.something
FROM tableA t1
LEFT JOIN tableB t2 ON t1.id = t2.TableA_Id
JOIN tableB t3 ON t3.TableA_Id = 0
JOIN tableC t4 ON t1.id = t4.TableA_Id

TableB必須只包含一行TableB.TableA_Id = 0。如果沒有,那麼使用

SELECT t1.name,
      COALESCE(t2.tag, t3.tag) tag,
      t4.something
FROM tableA t1
LEFT JOIN tableB t2 ON t1.id = t2.TableA_Id
CROSS JOIN ( SELECT *
            FROM tableB 
            WHERE TableA_Id = 0
            -- ORDER BY something, for example, by `Id`
            LIMIT 1 ) t3
JOIN tableC t4 ON t1.id = t4.TableA_Id

小提琴

引用自:https://dba.stackexchange.com/questions/283057