如何在sql中使用三个表中的子查询

时间:2018-01-18 08:56:23

标签: sql oracle11g

我有三张桌子,如:

customer

CUSTOMER#   LASTNAME    FIRSTNAME
1001    MORALES         BONITA
1002    THOMPSON        RYAN
1003    SMITH           LEILA
1004    PIERSON         THOMAS
1005    GIRARD          CINDY

orders

ORDER#  CUSTOMER#   ORDERDATE
1000    1005    31/MAR/09
1001    1010    31/MAR/09
1002    1011    31/MAR/09
1003    1001    01/APR/09

orderitems

ORDER#  ITEM#   ISBN    QUANTITY
1000    1   3437212490  1
1001    1   9247381001  1
1001    2   2491748320  1
1002    1   8843172113  2

我的问题是:如何打印订购超过1件商品的客户名称(数量超过1件?

我的SQL查询是这样的:

SELECT c.firstname, c.lastname
FROM customers c
WHERE (SELECT o.quantity FROM orderitems WHERE o.quantity > 1) 

上述查询中的错误是什么?

5 个答案:

答案 0 :(得分:2)

这应该这样做:

select c.firstname, c.lastname
from customer c
    join orders o on c.customer# = o.customer#
    join orderitems oi on o.order# = oi.order#
group by c.firstname, c.lastname
having sum(oi.quantity) > 1

答案 1 :(得分:1)

您的查询中有两个错误:

1)你没有真正比较任何事情。

where (select o.quantity from orderitems where o.quantity > 1) 

查询结果是数量大于1的行。所以你可能会得到

where (2
       3
       4) 

你可以清楚地看到,这没有任何意义。

2)您的子查询与相关客户记录无关。

它只是查找大量订单,无论客户是谁。

有关数量>的订购项目的解决方案1

(目前还不清楚你是否想要这个,或者你是否想要查看金额以及这些金额是按客户,每个订单,每个项目还是其他任何金额。请在您的请求的评论部分查看我的问题。)

您可以使用EXISTSIN执行此操作。例如:

select firstname, lastname
from customers
where customer# in 
(
  select customer# 
  from order
  where order# in (select order# from orderitems where quantity > 1)
);

答案 2 :(得分:0)

如下所示:

select c.firstname, c.lastname
from customers c
join orders on c.CUSTOMER#=orders.CUSTOMER#
join orderitems on orders.ORDER#=orderitems.ORDER#
group by c.firstname, c.lastname
having sum(orderitems.quantity)>1

您可以在没有join的情况下执行此操作,如下所示:

select c.firstname, c.lastname
from customers c
where 1 < (
            select sum(quantity) from orderitems where ORDER# in 
                (
                    select ORDER# from orders where CUSTOMER# = c.CUSTOMER#
                ) 
            group by ORDER#)

答案 3 :(得分:0)

Select c.first, c.Lastname, oi.quantity from customers c
inner join Orders o on c.customer = o.customers
inner join OrderItems oi on oi.order = o.order
where oi.quantity >= 1  

我想这可以帮助您解决问题

答案 4 :(得分:0)

您应该在HAVING中使用两个条件来满足who order more than 1 items(having quantity more than 1)

的条件
SELECT c.firstname, c.lastname
FROM customer c
JOIN orders o ON c.customer# = o.customer#
JOIN orderitems oi ON o.order# = oi.order#
GROUP BY c.firstname, c.lastname
HAVING SUM(oi.quantity) > 1 AND SUM(oi.ITEM#) > 1