mysql rows where count(x) > 1 and count(y) > 0

时间:2015-05-24 20:29:37

标签: mysql

I have a sales table containing invoice number, product code, product category, qty, etc.

Using this table how would you go about finding invoices that contain at least one product from say category A AND 1 product from category B ?

2 个答案:

答案 0 :(得分:0)

Okay, here's what I believe is what you'll want. Happy to see any simpler suggestions if anyone has them:

Select tableA.invoiceNumber
from 
(select * from myTable
where productCategory = 'A') tableA
inner join
(select * from myTable
 where productCategory = 'B') tableB
 on tableA.invoiceNumber = tableB.invoiceNumber

Here's a SQLFiddle:

http://sqlfiddle.com/#!9/03ddd/3

It's basically joining your query onto itself where there's a condition for each table on category.

答案 1 :(得分:0)

Try this :

    select * from mytable
inner join(
select invoiceNumber
from mytable
where mytable.productcategory = 'A'
) as a using (invoiceNumber)
inner join(
select invoiceNumber
from mytable
where mytable.productcategory = 'B') as b
using (invoiceNumber)
group by invoicenumber