【问题标题】:SQL Querying in multiple tables多表SQL查询
【发布时间】:2017-02-16 02:10:52
【问题描述】:

我有两张表,customers 和 Orders

客户列是

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

订单列是

OrderID,
CustomerID,
Date,
Time,
Price,
Complete

我想从所有已完成的订单中选择所有名字和姓氏。是的,可能是 [0] = John Smith 并且 [1] 也 = John Smith。

我的想法是

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

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

感谢您的帮助!!!

【问题讨论】:

  • 提示:将日期和时间存储为单个实体

标签: mysql sql


【解决方案1】:

您可以使用 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

【讨论】:

  • Group by 不起作用,因为如果多个订单具有相同的客户,则 OP 想要重复。
【解决方案2】:

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

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

【讨论】:

  • 谁支持这个东西?你不能简单地编造语法。
【解决方案3】:

我会亲自去:

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

我喜欢尽可能明确地处理我的查询,这样任何必须阅读我的代码的人都可以理解其中的内容、原因和方式。尽管您不应该也选择一些东西来识别订单吗?否则你只有一个名字列表。

【讨论】:

    【解决方案4】:
    --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 字词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2015-08-19
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多