Select values that meet different conditions on different rows?

前端 未结 6 1999
甜味超标
甜味超标 2020-11-22 07:37

This is a very basic query I can\'t figure out....

Let\'s say I have a two column table like this:

userid  |  roleid
--------|--------
   1    |    1         


        
6条回答
  •  无人及你
    2020-11-22 08:16

    The classic way to do this is to treat it as a relational division problem.

    In English: Select those users for whom none of the desired roleid values is missing.

    I'll assume you have a Users table to which the UserRole table refers, and I'll assume the desired roleid values are in a table:

    create table RoleGroup(
      roleid int not null,
      primary key(roleid)
    )
    insert into RoleGroup values (1);
    insert into RoleGroup values (2);
    insert into RoleGroup values (3);
    

    I'll also assume all the relevant columns are not NULLable, so there are no surprises with IN or NOT EXISTS. Here's a SQL query that expresses the English above:

    select userid from Users as U
    where not exists (
      select * from RoleGroup as G
      where not exists (
        select R.roleid from UserRole as R
        where R.roleid = G.roleid
        and R.userid = U.userid
      )
    );
    

    Another way to write it is this

    select userid from Users as U
    where not exists (
      select * from RoleGroup as G
      where G.roleid not in (
        select R.roleid from UserRole as R
        where R.userid = U.userid
      )
    );
    

    This may or may not end up being efficient, depending on indexes, platform, data, etc. Search the web for "relational division" and you'll find a lot.

提交回复
热议问题