我有一个表 table1
,它有 3 列 column1、column2 和 column3
。
column1
和column2
是一个FOREIGN KEY
和另外两个表。但是 column3
中的数据来自 n 个表。
例如让我们考虑一下 Facebook。为了显示事件,它可能会维护一个表,该表可能有 user1 photoliked photo1
或 user1 statusliked status1
。所以在这种情况下,column3
不能是具有特定表的 FOREIGN KEY
。
现在有两种获取真实数据的方法-
第一种方式-
SELECT user_id,
verb_id,
CASE WHEN verb_id = photoliked THEN
(SELECT photo_name FROM photos WHERE photo_id = column3) -- getting the desired data from the third column
WHEN verb_id = statusliked THEN
(SELECT status FROM statustable WHERE status_id = column3)
ELSE '' END AS performedon
FROM table1
JOIN table2 ON user_id = user_id -- joining the first column
JOIN table3 ON verb_id = verb_id -- joining the second column
第二种方式-
SELECT user_id,
verb_id,
CASE WHEN verb_id = photoliked THEN
p.photo_name
WHEN verb_id = statusliked THEN
s.status
ELSE '' END AS performedon
FROM table1
JOIN table2 ON user_id = user_id -- joining the first column
JOIN table3 ON verb_id = verb_id -- joining the second column
LEFT JOIN photos p ON p.photo_id = column3 -- joining the column3 with specific table
LEFT JOIN statustable s ON s.status_id = column3
问题
这两种检索数据的方法中哪一种更好? 两个查询中哪个更便宜?
最佳答案
第二个会更快,原因是第一个包含所谓的相关子查询。子查询与来自主查询的记录相关。因此子查询需要为主查询中的每个匹配记录运行一次。在您的情况下,在确定主查询中 verb_id 的值之前,它无法运行子查询。需要运行大量查询。
第一个查询的 EXPLAIN 应该指出这个问题。当您在 EXPLAIN 中看到它时,它通常是一个危险信号。
关于mysql - MySQL 中的 LEFT OUTER JOIN 与 SUBSELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11112940/