我有一个表table1,其中有3列column1,column2和column3.
column1和column2是一个带有2个其他表的FOREIGN KEY.但是,第3列中的数据来自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,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中看到它时,它通常是一个红旗.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。