MySQL - Return number of rows matching query data?

淺唱寂寞╮ 提交于 2020-01-06 06:53:18

问题


I have a query as follows:

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

The only thing I need to do with this data is work out the number of rows returned (which I could do with mysqli -> num_rows;. However, I would like to know if there is a method to return the number of rows that match the query, without having to run num_rows?

For example, the query should return one row, with one result, number_of_rows.

I hope this makes sense!


回答1:


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

In this case, since you are not using any aggregate functions and the GROUP BY is merely to eliminate duplicates, you could also do:

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


来源:https://stackoverflow.com/questions/12181583/mysql-return-number-of-rows-matching-query-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!