【发布时间】: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 列:
- 1--> mp3
- 2--> 专辑
- 3--> 混音
我需要这样的查询:
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 解决方案会奏效。