MySQL - 选择一个计数大于另一个计数的id计数

时间:2013-12-05 22:05:40

标签: mysql

这里的sql语句很新,所以这个对我来说有点棘手。

我有两张桌子:已售出和产品。已售出(SID,UPC,日期)产品(UPC,名称,品牌)

我需要找到一个品牌超过另一个品牌的商店(sid)。

我认为它是这样的:

select count(*) from sold natural join product 
where count(brand = 'sony') > count(brand = 'samsung'); 

显然这无效......

1 个答案:

答案 0 :(得分:1)

SELECT COUNT(*)
FROM (
   SELECT SID
   FROM Sold
   JOIN product
   ON product.UPC = Sold.UPC -- otherwise we have a cartesian product
   GROUP BY SID -- if we need totals _by store_, we need to group on that.
   HAVING SUM(brand='sony') > SUM(brand='samsung')
) Totals.