我真的被这个问题困住了。我需要创建一个查询,其中我有一个包含CustomerID和PurchaseID号的表。在另一个表中,我有CustomerID以及客户的FirstName和LastName。我需要做的只是获得记录的PurchaseID为1或2或7的客户的FirstName和LastName。当我尝试我的代码时,我从第二个tabel(包含FirstName,LastName,和CustomerID),这是不正确的。
这是我的代码:
SELECT FirstName, LastName
FROM Customer, Purchase
WHERE Purchase.PurchaseID = '1'
OR Purchase.PurchaseID = '2'
OR Purchase.PurchaseID = '7'
GROUP BY FirstName, LastName;
我是SQL的新手,非常感谢这里的帮助。
答案 0 :(得分:2)
SELECT DISTINCT c.FirstName, c.LastName
FROM Customer c
JOIN Purchase p ON p.CustomerID = c.CustomerID
WHERE p.PurchaseID IN ('1', '2', '7')
ORDER BY c.LastName, c.FirstName
更新:为了回应@David Aldridge的评论,我刚刚使用最新的服务包测试了SQL SERVER 2008 R2上的两个表单(他和我的)。他们生成 IDENTICAL 成本执行计划。事实上,我的连接形式的逻辑读取数量略低(但可能会因实际ID的选择而有所不同)
我针对SQL Server示例数据库AdventureWorksDW2008运行了这两个查询(因为David提到“我已经在数据仓库工作过了”):
select distinct c.FirstName, c.LastName
from dbo.FactInternetSales s
join dbo.DimCustomer c on c.CustomerKey = s.CustomerKey
where s.ProductKey IN (328, 333, 472)
SELECT FirstName,
LastName
FROM dbo.DimCustomer c
where exists (
select null
from dbo.FactInternetSales s
WHERE s.CustomerKey = c.CustomerKey and
s.ProductKey in (328, 333, 472))
答案 1 :(得分:1)
尝试此查询:
SELECT C.FirstName, C.LastName
FROM Customer C
JOIN Purchase P ON P.CustomerID = C.CustomerID
WHERE P.PurchaseID IN ('1','2','7')
GROUP BY C.FirstName, C.LastName
检查此SQL Fiddle test code以防万一,以确保其有效。增加了同一客户的几次购买,以确保不会重复结果。谢谢David Aldridge指出这一点。
还有另一个选项,使用EXISTS
作为David提出的答案。如果你有大表可以使用,应该有效地提高效率。使用该选项检查另一个SQL Fiddle test code。
避免使用旧的ANSI-89 JOIN语法,使用JOIN以获得更好的可读性:
FROM Customer, Purchase
WHERE Purchase.PurchaseID = '1'
检查Aaron Bertrands blog以获取有关它的更多信息
答案 2 :(得分:0)
SELECT FirstName, LastName
FROM Customer, Purchase
WHERE Customer.CustomerID = Purchase.CustomerID
AND ( Purchase.PurchaseID = '1' OR Purchase.PurchaseID = '2'
OR Purchase.PurchaseID = '7' )
正确的方法是在Mitchwheat回答中提到
答案 3 :(得分:0)
如果您想检查是否为客户购买了各种产品,请使用:
SELECT FirstName,
LastName
FROM Customer
where exists (
select null
from Purchase
WHERE Purchase.customerID = customer.customerid and
Purchase.PurchaseID in ('1','2','7'))
优化工具只需在购买表中找到一行就知道要包含该客户。
答案 4 :(得分:-1)
另一种方式,没有IN
:
SELECT DISTINCT c.FirstName, c.LastName
FROM Customer c
JOIN Purchase p ON p.CustomerID = c.CustomerID
WHERE
p.PurchaseID = '1' OR p.PurchaseID = '2'
OR p.PurchaseID = '7'
ORDER BY c.LastName, c.FirstName