如何正确编写此查询的语法? -
SELECT *
FROM `table_first`
LEFT JOIN `table_second` ON table_second.type_id1 = table_first.type_id1
直到这里一切都很好。现在出现了问题:
LEFT JOIN `table_third` ON
IF (table_first.id>10)
BEGIN table_third.id= table_first.type_id2 END
ELSE
BEGIN table_third.id = table_second.type_id2 END)
答案 0 :(得分:1)
您可以使用CASE-WHEN-ELSE-END:
SELECT *
FROM `table_first`
LEFT JOIN `table_second` ON table_second.type_id1 = table_first.type_id1
LEFT JOIN `table_third` ON table_third.id = CASE WHEN table_first.id > 10 THEN table_first.type_id2 ELSE table_second.type_id2 END;
根据每个WHEN中的条件,它返回THEN中的相应表达式。
答案 1 :(得分:1)
有什么问题?
SELECT *
FROM `table_first` LEFT JOIN
`table_second`
ON table_second.type_id1 = table_first.type_id1 LEFT JOIN
`table_third`
ON ((table_first.id > 10) and (table_third.id = table_first.type_id2)) or
((table_first.id <= 10) and (table_third.id = table_second.type_id2))
如果上一个条件没有匹配项,您将在NULL
的相应列中获得table_third
个。
编辑:
通常出于性能原因,您希望将其作为两个单独的连接执行,然后在coalesce()
子句中使用SELECT
:
SELECT . . ., coalesce(t3a.col1, t3b.col1) as col1, . . .
FROM `table_first` LEFT JOIN
`table_second`
ON table_second.type_id1 = table_first.type_id1 LEFT JOIN
`table_third` t3a
ON (table_first.id > 10) and (t3a.id = table_first.type_id2) LEFT JOIN
table_third t3b or
ON (table_first.id <= 10) and (t3b.id = table_second.type_id2)
这使数据库优化器更容易使用索引进行查询。