SQL:计算第3个表中的行数

时间:2016-06-30 07:56:20

标签: mysql sql

我有3个表,第一个表是account_has_account1,其中我存储了帐户之间的关系,它的列是account_id, account_id1, status,其中account_idaccount_id1后面的帐户} status是一个值为active, inactive的枚举类型,其中active表示该帐户是否实际关注,如果该帐户处于非活动状态,则帐户会停止跟踪。

第二个表名为account_has_photos,我存储了一个帐户存储在数据库中的照片,所以它的列是account_id, photos_id,所以我需要这个表来从一个帐户获取所有照片而另一个帐户帐户正在关注。

但是所有这些都有消息发布在他们身上,这里是第3个表名为photos_has_message_photos的地方,从这个表中我只需要计算一张照片中所有发布的消息,列是{{ 1}}

现在我的查询是:

photos_id, message_photos_id

它会显示帐户ID为7的帐户中的所有照片,但是我尝试收到的邮件总数失败了,我想这样做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"

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) 中选择,但它没有显示任何行,甚至没有显示照片,此时结果为空,我不知道为什么以及该做什么。

完整的查询是这样的:

posts.total

再次,我只需要从每张照片中找到消息的总行数

1 个答案:

答案 0 :(得分:1)

尝试此查询更新内部选择

 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"