返回只是在MYSQL查询中找到的记录数

时间:2013-11-15 13:43:37

标签: php mysql sql join subquery

我有以下MYSQL查询,该查询返回每张照片大于0的记录的照片数量。

SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve =  '1'
HAVING num_photos > 0

查询工作正常,但我想只返回找到的记录数。即具有至少一张照片的记录的数量。我试图用COUNT包装整个查询,但它给出了一个错误。我想在查询中执行此操作,而不是在php中找到单独的记录计数。

2 个答案:

答案 0 :(得分:3)

SELECT COUNT(*) AS TotalRecords 
FROM 
(
  SELECT a.advert_id, COUNT(*) AS num_photos
  FROM adverts AS a
    JOIN advert_images AS i
    ON i.advert_id = a.advert_id
  WHERE a.approve =  '1'
  GROUP BY a.advert_id
  HAVING num_photos > 0
) AS mq

答案 1 :(得分:0)

SELECT COUNT(*) FROM (SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve =  '1'
HAVING num_photos > 0) AS c

这应该可以解决问题