繁体   English   中英

编写高级sql查询

[英]writing advanced sql query

我正在使用以下架构: http : //classes.engr.oregonstate.edu/eecs/winter2013/cs275-400/tester/bsgSchema.html

我正在尝试实现:查找所有没有获得Viper认证但至少被分配给一个Viper级飞船实例(包括Viper级飞船的所有变体)的人的fname,lname和ship_instance id。 为每个船舶/人员组合返回一行。)

我近了 我写了以下查询:

SELECT DISTINCT p.fname, p.lname, si.id from bsg_people p
INNER JOIN bsg_ship_assignment sa ON sa.pid = p.id
INNER JOIN bsg_ship_class sc ON sc.id = sa.cid
INNER Join bsg_ship_instance si ON si.class = sa.cid
WHERE p.id NOT
IN (
    SELECT cp.pid
    FROM bsg_cert_people cp
    INNER JOIN bsg_cert c ON c.id = cp.cid
    WHERE cp.cid = '2'
)
AND sc.name = 'viper' 

我的查询返回了许多额外的实例。

SELECT p.fname
     , p.lname
     , sk.id
  FROM bsg_people p 
  LEFT 
  JOIN bsg_cert_people cp  
    ON cp.pid = p.id 
  LEFT 
  JOIN bsg_cert c 
    ON c.id = cp.cid 
   AND c.title = 'viper'
  JOIN bsg_ship_assignment ps
    ON ps.pid = p.id
  JOIN bsg_ship_instance sk
    ON sk.id = ps.sid
   AND sk.class = ps.cid
  JOIN bsg_ship_class k
    ON k.id = sk.class
 WHERE k.name = 'viper'
   AND c.id IS NULL;
+---------+----------+------+
| fname   | lname    | id   |
+---------+----------+------+
| William | Adama    | 8757 |
| Lee     | Adama    |  121 |
| Lee     | Adama    |  289 |
| Lee     | Adama    | 1104 |
| Laura   | Roslin   | 2343 |
| Gaius   | Baltar   |  289 |
| Samuel  | Anders   | 3203 |
| Samuel  | Anders   | 8757 |
| Brendan | Costanza | 7242 |
| Brendan | Costanza | 2343 |
+---------+----------+------+

从bsg_people中选择bsg_people.fname,bsg_people.lname,bsg_ship_instance.id

内联接bsg_ship_assignment ON bsg_ship_assignment.pid = bsg_people.id

内连接bsg_ship_instance ON bsg_ship_assignment.sid = bsg_ship_instance.id

内连接bsg_ship_class ON bsg_ship_class.id = bsg_ship_instance.class

bsg_people.id不在的位置

从bsg_cert_people选择bsg_cert_people.pid

内联bsg_cert ON bsg_cert_people.cid = bsg_cert.id

WHERE bsg_cert.title ='毒蛇'

AND bsg_ship_class.name ='毒蛇'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM