SQL在多个表中查询

时间:2017-02-15 15:49:12

标签: mysql sql

我有两个表,客户和订单

客户专栏

CustomerID,
Username,
Password,
Firstname,
Surname,
Email,
Mobile

订单列

OrderID,
CustomerID,
Date,
Time,
Price,
Complete

我想从所有已完成的订单中选择所有名字和姓氏。是的,可能是[0] =约翰史密斯和[1]也是约翰史密斯。

我在想的是

SELECT FirstName, Surname from order, customers
WHERE Complete = 'Yes' AND order.CustomerID = customer.CustomerID;

首先,它会查看订单是否完整。如果是,那么它将查看客户ID,然后它将转到客户并获取该客户的名字和姓氏,然后将其存储在数据表中。

感谢您的帮助!!!

4 个答案:

答案 0 :(得分:2)

您可以使用EXISTS,以下查询将返回所有不完整(= 0)订单的客户:

select c.firstname, c.lastname
from customers c
where
  not exists (select * from orders o
              where c.customerid = o.orderid
                    and o.complete = 'No')

但它也会返回没有订单的客户。如果要排除没有订单的客户,可以使用其他存在子句:

select c.firstname, c.lastname
from customers c
where
  not exists (select * from orders o
              where c.customerid = o.orderid
                    and o.complete = 'No')
  and exists (select * from orders o where c.customerid = o.orderid)

或group by子句:

select c.firstname, c.lastname
from customers c inner join orders o on c.customerid = o.customerid
group by c.customerid, c.firstname, c.lastname
having sum(o.complete='No') = 0

答案 1 :(得分:0)

即使他们没有订单,这也会为您提供名字,姓氏列表。

SELECT Customers.Firstname, Customer.Surname
FROM Customers, Orders
WHERE Orders.Complete = 'Yes'
LEFT JOIN Customers.CustomerID = Orders.CustomerID

答案 2 :(得分:0)

我个人会这样做:

SELECT c.Firstname, c.Surname FROM Customers c
INNER JOIN Orders o
ON c.CustomerID=o.CustomerID
WHERE o.Complete='Yes'

我希望尽可能明确地查询我的问题,因此任何必须阅读我的代码的人都能理解其中的内容,原因和方式。虽然你不应该选择一些东西来识别订单吗?否则你只有一个名单。

答案 3 :(得分:0)

--Unique list of customer id, customer first name and customer surname.
SELECT DISTINCT
    customers.customerid
    , customers.firstname
    , customers.surname
FROM        orders
INNER JOIN  customers 
ON 
    customers.customerid = orders.customerid
    AND orders.complete = 'Yes'

--Unique list of customer first name and customer surname, regardless 
--if same names are tied to different customerid.
SELECT DISTINCT
    customers.customerid
    , customers.firstname
    , customers.surname
FROM        orders
INNER JOIN  customers 
ON 
    customers.customerid = orders.customerid
    AND orders.complete = 'Yes'

如果您需要重复项,请删除 DISTINCT 字。