我有一个关于三个表的连接的查询。第3个表中的一列具有布尔值。 。表2和表3与product_id连接,表3上的每个product_id可以作为接收值与真值和假值相关联。我需要一个查询来返回表1中的所有记录,这些记录与表3中的接收值仅具有真值的产品相关联。 在下面的示例数据中,我只想返回GHI
Table 1 - Sale
ID sale#
1 ABC
2 DEF
3 GHI
Table 2 PO Table 1 join Table 2 on Table1.ID = Table 2.SaleID
ID SaleID
1 1
2 1
3 2
4 3
5 3
Table 3
ID POID Received Table 2 right join table 3 on Table 2.ID = Table 3.POID
1 1 True
2 1 False
3 2 True
4 3 False
5 4 True
6 5 True
7 5 True
在下午试验之后,我使用NOT IN使其工作,但是我的数据集(当前只有大约2000条记录)非常慢我认为这可能是因为它必须重新创建连接。似乎应该有一种更优雅的方式来实现这一目标。
SELECT Distinct Table1.id, Table3.received
FROM Table3 INNER JOIN (Table2 INNER JOIN Table1 ON Table2.saleID = Table1.id)
ON Table3.POID = Table2.id
WHERE ((Table3.received)=True) and Table1.id NOT IN (
SELECT Table1.id
FROM Table3 INNER JOIN (Table2 INNER JOIN Table1 ON Table2.saleID = Table1.id)
ON Table3.POID = Table2.id
WHERE ((Table3.received)=False));
答案 0 :(得分:0)
我相信这是您需要的查询
select Table1.* from Table1 join Table2 on Table1.id = Table2.saleid join table3 on table3.POID = Table2.ID where table3.received = true
答案 1 :(得分:0)
首先,只需从表3中选择具有表3中的真值输入的产品,这可以通过POID上的自联接来完成。然后结果可以与table2和table1
结合使用select
Table1.*
from
Table1 join Table2
on Table1.id = Table2.saleid
join
(select t3.poid
from
Table3 t3 join Table3 t4
on t.POID = Table4.POID)
where t3.received = true and t4.received = true) all_true
on all_true.POID = Table2.ID
答案 2 :(得分:0)
您需要做的就是确保特定count
的{{1}}条记录等于值sale#
= {的记录的count
{1}}又称count-if(在SQL中没有显式存在)。在SQL中完成count-if的方法是执行received
。
示例数据设置:
True
<强>答案:强>
...sum(case ... when ... then 1 else 0 end)...
<强>输出:强>
create table dbo.Sale
(
ID int
, sale# char(3)
)
create table dbo.PO
(
ID int
, SaleID int
)
create table dbo.Received
(
ID int
, POID int
, Received char(5)
)
insert into dbo.Sale
values (1, 'ABC'), (2, 'DEF'), (3, 'GHI')
insert into dbo.PO
values (1,1), (2,1), (3,2), (4,3), (5,3)
insert into dbo.Received
values (1, 1, 'True')
, (2, 1, 'False')
, (3, 2, 'True')
, (4, 3, 'False')
, (5, 4, 'True')
, (6, 5, 'True')
, (7, 5, 'True')
答案 3 :(得分:0)
谢谢tarheel 你把我放在了赛道上。我做了一个真/假,并添加了Sum(已接收)=计数(已接收)
SELECT DISTINCT Table1.id
FROM Table3 INNER JOIN (Table2 INNER JOIN Table1 ON Table2.saleID = Table1.id) ON Table3.POID = Table2.id
GROUP BY Table1.id
HAVING (-1*(Sum(Table3.received))=Count([Table3].[received]));