我有一张桌子说它table1
有 3 列column1, column2 and column3
。
和是一个column1
与其他 2 个表。但是,其中的数据来自 n 个表。column2
FOREIGN KEY
column3
例如,让我们考虑 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
问题
两种方法中哪一种更好地检索数据?两个查询中哪一个更便宜?