【问题标题】:How do I SELECT all values NOT related to a record如何选择与记录无关的所有值
【发布时间】:2021-10-10 22:56:47
【问题描述】:

Table1 = 用户(字段:id、用户名)

Table2 = (字段:id、组名)

(用户可以通过table3分配到多个组)

Table3 = usr_grp(字段:userid、groupid)

这个查询告诉我 ALL 与 userid=1 相关的组

SELECT g.groupname FROM groups g INNER JOIN usr_grp u ON u.groupid=g.id WHERE u.userid=1

mysql 查询会返回 ALL userid=1 NOT 分配给的组名吗?

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:
    select g.groupname
    from groups g
    left join user_grp u on u.groupid=g.id and u.userid=1
    where u.groupid is null
    

    或同等的

    select g.groupname
    from groups g
    where not exists (
        select 1 from user_grp u
        where u.userid=1 and u.groupid=g.id
    )
    

    select g.groupname
    from groups g
    where g.id not in (select groupid from usr_grp where userid=1)
    

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2023-02-22
      • 2018-10-08
      相关资源
      最近更新 更多