如果存在某个值,我需要查找ID的所有其他相关记录。
我几乎没有SQL经验,主要在前端设计UI上工作,而不是自己编写代码。
基本查询是:
在给定期间内,如果有任何客户在该期间下订单,我希望查看这些客户的所有订单。
因此,寻找四月份下订单的所有客户的所有订单:
Customer Order Month
John Apples January
John Pears January
John Oranges February
John Bananas April
Amy Apples March
Amy Pears May
Amy Oranges July
Amy Bananas September
Larry Apples January
Larry Pears April
Larry Oranges August
Larry Bananas November
Marge Apples April
Marge Pears May
Marge Oranges June
Marge Bananas July
预期结果将是:
Customer Order Month
John Apples January
John Pears January
John Oranges February
John Bananas April
Larry Apples January
Larry Pears April
Larry Oranges August
Larry Bananas November
Marge Apples April
Marge Pears May
Marge Oranges June
Marge Bananas July
我们将不胜感激。
答案 0 :(得分:1)
一种可能性是使用EXISTS
和一个相关子查询,该查询检查名称是否从4月开始记录。
SELECT *
FROM elbat t1
WHERE EXISTS (SELECT *
FROM elbat t2
WHERE t2.name = t1.name
AND t2.month = 'April');
另一种方法是对4月份的所有记录使用派生表,并以通用名称连接其他记录。
SELECT t2.*
FROM (SELECT t1.name
FROM elbat t1
WHERE t1.month = 'April') x
INNER JOIN elbat t2
ON t2.name = x.name;
答案 1 :(得分:0)
我会按照您的描述来写它:查找四月份的所有客户,然后显示这些客户的所有订单。
SELECT * FROM OrderTable ot WHERE ot.Customer IN
(SELECT DISTINCT Customer FROM OrderTable WHERE Month = 'April')