【问题标题】:need to join table on based of condition in mysql需要根据mysql中的条件加入表
【发布时间】:2013-04-01 12:11:44
【问题描述】:

我想在 iOS/android 应用程序中集成类似的功能。 我正在为此开发服务。 我的问题是: 我有一个名为歌曲的表,其中有歌曲的详细信息

**like**

song
song_id
station_id
song_file

等等。 我有第二个名为 userlike 的表,其中存储了用户喜欢的信息。

**userlike**
user_id
song_id
like

我的主要问题是我想返回所有歌曲详细信息以及特定用户的类似值信息。如果用户不喜欢它,那么我可以在我的 JSON 中发送“零”或 null。 如何构建此查询? 如果用户喜欢,我需要歌曲数据和点赞值。

【问题讨论】:

标签: mysql join outer-join


【解决方案1】:

试试这个

select s.song, s.song_id from song s , userlike u where u.user_id = your userId;

【讨论】:

    【解决方案2】:

    假设userlike.likeboolean

    SELECT like.song, like.song_id,
     like.station_id,
     like.song_file,
    IFNULL(userlike.like,0)
    from like left join userlike on like.song_id=userlike.song_id
    and userlike.user_id=/*your userid*/
    

    【讨论】:

      【解决方案3】:

      听起来你需要使用OUTER JOIN

      SELECT s.song_id, s.song, u.like
      FROM song s 
          LEFT JOIN userlike u 
              ON s.song_id = u.song_id 
                  AND u.user_id = @userId
      

      将 userId 放入 Join 将确保返回歌曲,即使用户不喜欢它。

      【讨论】:

        【解决方案4】:
        select songs.song_id as song_id , songs.station_id as station_id , songs.song_file as song_file , userlike.user_id as user_id ,  COALESCE(userlike.like, 0) as like 
                    FROM songs LEFT JOIN userlike
                    on songs.song_id = userlike.song_id
                    and userlike.user_id = 'your particular user'
        

        上面的 sql 应该可以工作。请查找表名和列名进行更正。

        谢谢

        【讨论】:

          猜你喜欢
          • 2013-03-24
          • 2019-03-19
          • 2020-04-29
          • 1970-01-01
          • 1970-01-01
          • 2016-04-12
          • 2021-08-27
          • 1970-01-01
          • 2019-12-22
          相关资源
          最近更新 更多