来自表的简单SQL查询

时间:2018-04-10 16:49:55

标签: sql phpmyadmin

对于我的CIS类,我有SQL项目,这是我第一次使用SQL,做得很好,但我不能做其中一个查询。任何帮助将不胜感激。

这就是我的尝试:

Select cno, cname
from customer
where 
                )
            )
        )

2 个答案:

答案 0 :(得分:2)

只需使用两个IN条款,一个用于财务会计'一个用于'成本会计'。

Select cno, cname
from customer
where cno in 
(
  select cno
  from salesorder
  where ono in 
  (
    select ono 
    from orderline 
    where bno in (select bno from book where bname = 'Financial Accounting')
  )
)
and cno in 
(
  select cno
  from salesorder
  where ono in 
  (
    select ono 
    from orderline 
    where bno in (select bno from book where bname = 'Cost Accounting')
  )
);

Rob M的解决方案更优雅,而上述查询应该更符合您迄今为止所学到的知识。

答案 1 :(得分:1)

您并不清楚客户是需要订购一个订单还是多个订单。我将根据提供的数据假设后者。

您的回答是退回订购其中一本(或两本)书籍的客户。你说你想要订购这两本书的顾客。此外,在嵌套多个子查询时,很难保持代码的正确性。大多数人更喜欢加入。

此查询应该适合您。

select cno,cname from customer where cno in (
    select o.cno
    from salesorder o  
        inner join orderline ol on o.ono=ol.ono
        inner join book b on b.bno=ol.bno
    where b.bname in ('Financial Accounting', 'Cost Accounting')
    group by o.cno
    having count(distinct b.bno) = 2 -- Require both separate books, not 2 of one book or the other      
)

以下是SQL Server中的完整示例:

declare @book table (bno int, bname varchar(50))
insert @book (bno,bname) values
(10501,'Forensic Accounting')
,(10704,'Financial Accounting')
,(10933,'Cost Accounting')
declare @orderline table (ono int, bno int) 
insert @orderline (ono,bno) VALUES
(1020,10501)
,(1020,10502)
,(1020,10503)
,(1020,10504)
,(1021,10605)
,(1022,10605)
,(1022,10704)
,(1023,10879)
,(1023,10988)
,(1024,10502)
,(1024,10988)
,(1026,10933)
,(1027,10933)
,(1028,10933)
,(1028,10965)
,(1029,10933)
,(1029,10965)
,(1029,10988)
,(1030,10965)
declare @salesorder table (ono int, cno int)
insert @salesorder (ono,cno) VALUES
(1020,23511)
,(1021,23513)
,(1022,23513)
,(1023,23512)
,(1024,23511)
,(1025,23511)
,(1026,23511)
,(1027,23512)
,(1028,23512)
,(1029,23513)
,(1030,23511)
declare @customer table (cno int, cname varchar(20))
insert @customer (cno,cname) values 
(23511,'a')
,(23512,'b')
,(23513,'c')
,(23514,'d')
,(23515,'e')
,(23516,'f')
,(23517,'g')
,(23518,'h')

select cno,cname from @customer where cno in (
    select o.cno
    from @salesorder o  
        inner join @orderline ol on o.ono=ol.ono
        inner join @book b on b.bno=ol.bno
    where b.bname in ('Financial Accounting', 'Cost Accounting')
    group by o.cno
    having count(distinct b.bno) = 2 -- Require both separate books, not 2 of one book or the other      
)