2017-01-31 123 views
1

我必須從3個表中選擇數據。我使用第一個和第二個表之間的INNER JOIN從第二個表中獲取另一個字段。但如果有不匹配,我有另1臺field.I來取代它現在用下面的查詢,但時間太長process.Is有另一種方式做到這一點替代聯盟運營商

SELECT tba.field, tba.field1, tba.field2 AS test FROM tablea tba 
    WHERE tba.field NOT IN (SELECT ta.field FROM tablea ta INNER JOIN tableb tb ON ta.field = tb.field) 
UNION 
SELECT ta.field, ta.field1, tb.field2 AS test FROM tablea ta 
    INNER JOIN tableb tb ON ta.field = tb.field 
UNION 
SELECT tc.field, tc.field1, tc.field2 AS test FROM tablec tc 

SQL fiddle

+4

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-看起來對我來說是一個非常簡單的sql查詢 - 並且注意關於查詢性能的問題總是要求至少爲所有相關表顯示CREATE TABLE語句,說明。 – Strawberry

+0

你是否在使用子查詢而不是第二個查詢聯合是相同的。爲什麼? –

+0

@strawberry我添加了鏈接。 – khalil

回答

0

這樣的事情就夠了:

SELECT tba.field, tba.field1, COALESCE(tb.field2, tba.field2) AS test 
FROM tablea tba 
LEFT OUTER JOIN tableb tb ON tba.field = tb.field 
UNION 
SELECT tc.field, tc.field1, tc.field2 AS test FROM tablec tc 
0

試試這個:這裏是查詢的替代方法,如果數據不重複,也可以使用UNION ALL而不是UNIONUNION ALL比較快

SELECT ta.field1, ta.field2, IFNULL(tb.field2, ta.field3) AS mytest 
FROM tablea ta 
LEFT JOIN tableb tb ON ta.field3 = tb.field1 
UNION ALL 
SELECT tc.field1, tc.field2, tc.field3 AS mytest FROM tablec tc