简体   繁体   English

MySQL复杂选择查询表5

[英]Mysql Complex Select Query in 5 table

I have 5 table: 我有5张桌子:

  1. mp3s mp3
  2. albums 专辑
  3. remixes 混音
  4. users 使用者
  5. likes 喜欢

likes table: 喜欢表:

╔════════╦══════════╦═════════╦═════════════╦═════════════════════╗
║ 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 columns: type_id列:

  • 1--> mp3s 1-> mp3
  • 2--> albums 2->专辑
  • 3--> remixes 3->混音

i need this query like: 我需要这样的查询:

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

thanks. 谢谢。

You'll need to use unions and joins 您需要使用联合和联接

This selects all of the valid mp3 rows. 这将选择所有有效的mp3行。

select 
    col1, col2, col3
from 
    likes
inner join
    mp3s
on likes.target_id = mp3s.id
where likes.type_id = 1 -- type is mp3

Now, so I dont do all the work for you -- create two more queries to get just the remixes and just the albums -- and then join them, maybe with a union? 现在,让我不为您做所有工作-再创建两个查询以获取混音和专辑-然后加入他们,也许可以加入工会?

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM