Query
查詢數據有問題
我在從表中檢索數據時遇到困難。
貝婁是我陷入困境的場景。
TableA
TableB
TableC
TableA
joins WithTableB
byTableA_Id
column,唯一的區別是如果沒有TableA
id 的引用,那麼我們應該返回帶有TableA_Id = 0
from的行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