0

我有如下的sql:

PRAGMA foreign_keys = 1;

CREATE TABLE people ( pid INTEGER   PRIMARY KEY, name TEXT );
CREATE TABLE groups ( gid INTEGER   PRIMARY KEY, name TEXT );

CREATE TABLE p_g_bridge (
        pid INTEGER   NOT NULL   REFERENCES people,
    gid INTEGER   NOT NULL   REFERENCES groups,
    PRIMARY KEY ( pid, gid )
);


-- people
INSERT INTO people VALUES ( 1, 'Alice' );
INSERT INTO people VALUES ( 2, 'Bob' );
INSERT INTO people VALUES ( 3, 'Charlie' );

-- groups
INSERT INTO groups VALUES ( 1, 'users' );
INSERT INTO groups VALUES ( 2, 'admin' );
INSERT INTO groups VALUES ( 3, 'web' );
INSERT INTO groups VALUES ( 4, 'db' );
INSERT INTO groups VALUES ( 5, 'nobody' );



-- everyone in users
INSERT INTO p_g_bridge VALUES ( 1, 1 );
INSERT INTO p_g_bridge VALUES ( 2, 1 );
INSERT INTO p_g_bridge VALUES ( 3, 1 );

-- Alice and Bob into admin
INSERT INTO p_g_bridge VALUES ( 1, 2 );
INSERT INTO p_g_bridge VALUES ( 2, 2 );

-- Charlie into web
INSERT INTO p_g_bridge VALUES ( 3, 3 );

-- Alice and Charlie into db
INSERT INTO p_g_bridge VALUES ( 1, 4 );
INSERT INTO p_g_bridge VALUES ( 3, 4 );

下面是表格:

select * from groups;
gid         name      
----------  ----------
1           users     
2           admin     
3           web       
4           db        
5           nobody    
sqlite> select * from people;
select * from people;
pid         name      
----------  ----------
1           Alice     
2           Bob       
3           Charlie   

sqlite> select * from p_g_bridge;
select * from p_g_bridge;
pid         gid       
----------  ----------
1           1         
2           1         
3           1         
1           2         
2           2         
3           3         
1           4         
3           4         

我希望查询所有都是“用户”的人,即)结果必须如下:

pid         name      
----------  ----------
1           Alice     
2           Bob       
3           Charlie   

我写一个这样的查询:

sqlite> select * from people where people.pid = (select p_g_bridge.pid from p_g_bridge where p_g_bridge .gid = (select groups.gid from groups where groups.name = 'users'));

IT 给出的结果如下:

pid         name      
----------  ----------
1           Alice     

但是查询必须返回如上所述的结果。

4

2 回答 2

1

IN不希望=您的子选择。 IN检查成员资格,=从子查询中提取一个值(第一个,最后一个,它是特定于实现的),或者当有多个结果时抛出错误。

select *
from people
where people.pid IN 
    (
    select p_g_bridge.pid
    from p_g_bridge
    where p_g_bridge.gid IN
        (
        select groups.gid
        from groups
        where groups.name = 'users'
        )
    );
于 2012-09-22T07:10:19.017 回答
0

试试这个,告诉我结果是什么

select people.pid, people.name
where
people.pid=p_g_bridge.pid
and
groups.pid=p_g_bridge.gid
and
groups.name = 'users'
于 2012-09-22T07:10:50.727 回答