[英]SQL: count rows from 3rd table
我有3个表,第一个表是account_has_account1
,我在其中存储帐户之间的关系,它的列是account_id, account_id1, status
,其中account_id
是紧跟account_id1
的帐户, status
是具有值active, inactive
的枚举类型active, inactive
表示active
如果该帐户实际上在关注,如果该帐户处于非活动状态,则该帐户停止关注。
第二张表名为account_has_photos
,它存储一个帐户已存储在数据库中的照片,因此它的列是account_id, photos_id
,因此我需要此表从另一个帐户正在关注的一个帐户中获取所有照片。
但是所有这些都有张贴在上面的消息,这是第3个表,名为photos_has_message_photos
,从该表中我只需要统计一张照片中所有已发布消息的数量,列是photos_id, message_photos_id
现在我的查询是这样的:
SELECT account_has_photos.photos_id as id, "photos" as type, account_has_photos.update_at, account_has_photos.account_id
FROM account_has_account1
JOIN account_has_photos
ON (account_has_photos.account_id = account_has_account1.account_id1 AND account_has_photos.type_id = 17)
WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active"
它显示了帐户ID为7的帐户中的所有照片,但是在我尝试获取总消息时失败了,我想到进行这样的INNER JOIN
:
INNER JOIN (
SELECT photos_has_message_photos.photos_id, count(photos_has_message_photos.photos_id) as total
FROM photos_has_message_photos
) posts
ON(posts.photos_id = account_has_photos.photos_id)
然后我从main posts.total
选择,但是它不显示任何行,甚至不显示照片,此时结果为空,我不知道为什么以及要做什么。
完整的查询是这样的:
SELECT account_has_photos.photos_id as id, "photos" as type, account_has_photos.update_at, account_has_photos.account_id, posts.total
FROM account_has_account1
JOIN account_has_photos
ON (account_has_photos.account_id = account_has_account1.account_id1 AND account_has_photos.type_id = 17)
INNER JOIN (
SELECT photos_has_message_photos.photos_id, count(photos_has_message_photos.photos_id) as total
FROM photos_has_message_photos
) posts
ON(posts.photos_id = account_has_photos.photos_id)
WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active"
再次,我只需要一共行,这些行是发现的每张照片的消息
尝试此查询更新内部选择
SELECT ahp.photos_id as id, "photos" as type, ahp.update_at, ahp.account_id,posts.total
FROM account_has_account1
JOIN account_has_photos
ON (ahp.account_id = account_has_account1.account_id1 AND ahp.type_id = 17) INNER JOIN (
SELECT phmp.photos_id, count(*) as total FROM photos_has_message_photos GROUP BY phmp.photos_id
) posts
ON(posts.photos_id = ahp.photos_id) WHERE account_has_account1.account_id = 7 AND account_has_account1.`status` = "Active"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.