我有一个表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
题
最佳答案