MySQL - 返回与查询数据匹配的行数?

时间:2012-08-29 15:37:41

标签: mysql group-by mysql-num-rows

我的查询如下:

SELECT 1 FROM shop_inventory a JOIN shop_items b ON b.id=a.iid AND b.szbid=3362169 AND b.cid=a.cid WHERE a.cid=1 GROUP BY a.bought

我需要对这些数据做的唯一事情是计算出返回的行数(我可以使用mysqli -> num_rows;。但是,我想知道是否有一种方法可以返回数量与查询匹配的行,而不必运行num_rows

例如,查询应返回一行,结果为number_of_rows

我希望这是有道理的!

1 个答案:

答案 0 :(得分:4)

select count(*) as `number_of_rows`
from (
    select 1
    from shop_inventory a
    join shop_items b on b.id = a.iid
        and b.szbid = 3362169
        and b.cid = a.cid
    where a.cid = 1
    group by a.bought
) a

在这种情况下,由于您没有使用任何聚合函数,GROUP BY仅仅是为了消除重复项,您还可以这样做:

select count(distinct a.bought) as `number_of_rows`
from shop_inventory a
join shop_items b on b.id = a.iid
    and b.szbid = 3362169
    and b.cid = a.cid
相关问题