Mysql Complex在5表中选择查询

时间:2016-06-07 16:40:53

标签: jquery mysql sql database mysqli

我有5张桌子:

  1. 的MP3
  2. 相册
  3. 混音
  4. 用户
  5. 喜欢
  6. 喜欢桌子:

    ╔════════╦══════════╦═════════╦═════════════╦═════════════════════╗
    ║ 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
    

    感谢。

2 个答案:

答案 0 :(得分: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

现在,所以我不为你做所有的工作 - 再创建两个查询来获得混音和专辑 - 然后加入他们,也许加入工会?

答案 1 :(得分:1)

试试这个:

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