Sql 从表中选择,其中一个值存在,其他值不存在
我有两张桌子——产品和发票 发票表具有此结构Sql 从表中选择,其中一个值存在,其他值不存在,sql,database-design,Sql,Database Design,我有两张桌子——产品和发票 发票表具有此结构 invoiceId productId invoiceType invoiceType具有以下值: 形式 艾文斯 最终的 我如何从products表中选择产品,这些产品在Invoice表的InvoiceType列中只有'proforma'值,而没有其他两个avans,final?您的sql应该如下所示,而不知道确切的字段名。这是我能做的最好的选择: Select * from products p where Exists (Sel
invoiceId
productId
invoiceType
invoiceType具有以下值:
形式
艾文斯
最终的
我如何从products表中选择产品,这些产品在Invoice表的InvoiceType列中只有'proforma'值,而没有其他两个avans,final?您的sql应该如下所示,而不知道确切的字段名。这是我能做的最好的选择:
Select * from products p
where Exists
(Select * from Invoices
Where productId = p.productId
and invoiceType = 'proforma')
and Not Exists
(Select * from Invoices
Where productId = p.productId
and invoiceType in ('avans', 'final'))
从发票中选择*
在products.productid=invoices.productid上内部联接产品
其中invoices.invoicetype='proforma'一种方法使用的存在和不存在:
这应该是对数据库的1次完整扫描:
select *
from Products p
join (
select i.productId
from Invoice i
group by i.productId
having max(case when i.nvoiceType = 'proforma' then 1 else 2 end) = 1) iSum
on P.productId = iSum.productID
order by p.productId
只是好奇:艾文斯是什么意思?
select *
from Products p
join (
select i.productId
from Invoice i
group by i.productId
having max(case when i.nvoiceType = 'proforma' then 1 else 2 end) = 1) iSum
on P.productId = iSum.productID
order by p.productId