5表中的复杂选择查询
Posted
技术标签:
【中文标题】5表中的复杂选择查询【英文标题】:Complex Select Query in 5 table 【发布时间】:2016-10-07 16:17:36 【问题描述】:我有 5 张桌子:
-
mp3
专辑
混音
用户
喜欢
喜欢表:
╔════════╦══════════╦═════════╦═════════════╦═════════════════════╗
║ id ║ user_id ║ type_id ║ target_id ║ like_date ║
╠════════╬══════════╬═════════╬═════════════╬═════════════════════╣
║ 1 ║ 1 ║ 1 ║ 1049 ║ 2016-05-23 19:50:41 ║
╠════════╬══════════╬═════════╬═════════════╬═════════════════════╣
║ 2 ║ 2 ║ 2 ║ 457 ║ 2016-01-09 19:50:42 ║
╠════════╬══════════╬═════════╬═════════════╬═════════════════════╣
║ 3 ║ 2 ║ 3 ║ 457 ║ 2016-01-09 19:50:42 ║
╠════════╬══════════╬═════════╬═════════════╬═════════════════════╣
║ 4 ║ 2 ║ 1 ║ 457 ║ 2016-01-09 19:50:42 ║
╠════════╬══════════╬═════════╬═════════════╬═════════════════════╣
║ 5 ║ 3 ║ 3 ║ 4955 ║ 2016-06-12 19:50:41 ║
╚════════╩══════════╩═════════╩═════════════╩═════════════════════╝
type_id
列:
我需要这样的查询:
select col1, col2, col3
from likes, mp3s, albums, remixes
where likes.user_id == 2
if (likes.type_id == 1)
select col1, col2, col3
from mp3s
where likes.target_id == mp3s.id
union
if (likes.type_id == 2)
select col1, col2, col3
from albums
where likes.target_id == albums.id
union
if (likes.type_id == 3)
select col1, col2, col3
from remixes
where likes.target_id == remixes.id
order by likes.like_date desc
limit 0,20
【问题讨论】:
问题出在哪里? @juergend 将上述查询转换为正确查询:| 顺便说一下,这种建模称为多态关联 @ShadyAtef 有什么解决办法? @grizzly 我相信 gbtimmon 解决方案会奏效。 【参考方案1】:你需要使用联合和连接
这会选择所有有效的 mp3 行。
select
col1, col2, col3
from
likes
inner join
mp3s
on likes.target_id = mp3s.id
where likes.type_id = 1 -- type is mp3
现在,我不为你做所有的工作——再创建两个查询来获取混音和专辑——然后加入它们,也许有一个联合?
【讨论】:
col1, col2, col3
是 mp3s, albums, remix
列
mp3s.mp3_name
, mp3s.mp3_title
, mp3s.mp3_size
order by like_date
很重要!
重命名子查询中的列,以便在使用 as
关键字联合后,它们按照您想要的方式组合在一起。通过将联合查询包装在对数据集进行排序的外部查询中来对结果集进行排序。
请编辑您的答案并使用union
和orderby
编写完整的解决方案查询。谢谢【参考方案2】:
试试这个:
SELECT IF(likes.type_id = 1, mp3s.col1, IF(likes.type_id = 2, albums.col1, remixes.col1)) col1,
IF(likes.type_id = 1, mp3s.col2, IF(likes.type_id = 2, albums.col2, remixes.col2)) col2,
IF(likes.type_id = 1, mp3s.col3, IF(likes.type_id = 2, albums.col3, remixes.col3)) col3
FROM
likes
LEFT JOIN mp3s
ON likes.type_id = 1 AND likes.target_id == mp3s.id
LEFT JOIN albums
ON likes.type_id = 2 AND likes.target_id == albums.id
LEFT JOIN remixes
ON likes.type_id = 3 AND likes.target_id == remixes.id
WHERE likes.user_id == 2
ORDER BY likes.type_id, likes.like_date desc
【讨论】:
以上是关于5表中的复杂选择查询的主要内容,如果未能解决你的问题,请参考以下文章