JHS*_*JHS 6 mysql sql join query-optimization
我有一张表说table1有3列column1, column2 and column3.
的column1和column2是一个FOREIGN KEY与其它2个表.但是,数据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
Run Code Online (Sandbox Code Playgroud)
第二路 -
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
Run Code Online (Sandbox Code Playgroud)
题
检索数据的两种方法中哪一种更好?哪两个查询更便宜?
第二个会更快,原因是第一个包含所谓的相关子查询。子查询与主查询中的记录具有相关性。因此,对于主查询中的每个匹配记录,都需要运行一次子查询。在您的情况下,在确定主查询中 verb_id 的值之前,它无法运行子查询。要运行很多查询。
第一个查询的 EXPLAIN 应指出此问题。当你在解释中看到这一点时,这通常是一个危险信号。