【问题标题】:Select "many to many" and "belongs to" in single statement在单个语句中选择“多对多”和“属于”
【发布时间】:2019-10-06 11:46:36
【问题描述】:
user_playlist
-------------
user_id
playlist_id

user
-------------
id
name

playlist
-------------
id
user_id
name

细分后,播放列表可以是公共的(使用联结表分配给用户)或私有的(通过设置播放列表 user_id 属于用户)。如何在一次选择中查询用户的所有播放列表?这甚至可能吗?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    此查询应为您提供所需的结果。 JOINs userplaylist,可以通过 user_playlist(用于公共播放列表)或直接(用于私人播放列表):

    SELECT DISTINCT p.id, p.name
    FROM user u
    LEFT JOIN user_playlist up ON up.user_id = u.id
    JOIN playlist p ON p.id = up.playlist_id OR p.user_id = u.id
    

    您只需添加适当的WHERE 子句(例如u.id = 4u.name = 'bill')来选择感兴趣的用户。

    Demo on dbfiddle

    【讨论】:

      【解决方案2】:

      我建议exists:

      select pl.*
      from playlist pl
      where pl.user_id = :user or
            exists (select 1
                    from user_playlist upl
                    where upl.play_list_id = pl.id and
                          upl.user_id = :user
                   );
      

      user 表实际上并不需要这样做,除非您想为 所有 用户运行查询或者您需要访问该名称。您的问题似乎一次只针对一个用户。

      【讨论】:

      • 没错。要访问所有用户的所有播放列表,我只需从播放列表表中进行选择。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2016-10-18
      • 1970-01-01
      • 2011-02-13
      相关资源
      最近更新 更多