计算特定ID的行数

时间:2016-02-18 07:22:53

标签: php mysql

在第一个表album中有{id},第二个表album_detailssub_id,与albumid

相关

enter image description here

enter image description here

我需要显示单独id值的计数。

SELECT DISTINCT B.SUB_ID, A . * , B.CONTENT_VALUE AS detail, 
(SELECT COUNT( ID ) 
FROM album_details WHERE A.ID = B.SUB_ID ) AS count
FROM album AS A, album_details AS B
WHERE A.WEBSITE_ID =  '571710720'
AND A.ID = B.SUB_ID
GROUP BY B.SUB_ID
LIMIT 0 , 30

现在,count列显示所有行的40,但需要为'id = 4'显示'count'6,为'id = 2'显示'count'3

4 个答案:

答案 0 :(得分:1)

假设第一个表是A,第二个表是B,那么查询将是这样的

select a.ID, count(b.SUB_ID) AS total
FROM A LEFT JOIN B ON A.ID = B.SUB_ID
Group by B.SUB_ID.

它可能对你有所帮助。如果没有,请问。

答案 1 :(得分:1)

GROUP BY是您的首选武器。

SELECT 
    a.ID,
    a.CONTENT_VALUE,
    COUNT(ad.ID)
FROM albums AS a
LEFT JOIN album_details AS ad ON a.ID = ad.SUB_ID
GROUP BY a.ID

您可以在WHERE之前添加GROUP BY

答案 2 :(得分:1)

从album_details中选择count(sub_id)作为count1,其中sub_id in(从专辑中选择id)WHERE album.WEBSITE_ID =' 571710720' AND album.ID = album_details.SUB_ID

答案 3 :(得分:1)

SELECT count(SUB_ID),来自album_details组的SUB_ID SUB_ID