在 SQL 中计算带有 where 子句的字段
Posted
技术标签:
【中文标题】在 SQL 中计算带有 where 子句的字段【英文标题】:Count fields with a where clause in SQL 【发布时间】:2011-10-25 04:19:58 【问题描述】:是否可以计算某些内容的字段?
我有以下查询:
SELECT * FROM
(SELECT messages.id as id,
messages.user_id,
messages.category_id,
messages.parent_id,
messages.message,
messages.create_date,
messages.update_date,
messages.status,
users.name as username,
users.id as userid,
users.email as useremail,
users.phone as userphone,
users.active as useractive,
users.role as userroel,
users.date as register_date
FROM `afo_messages` as messages
INNER JOIN `key_users` as users ON messages.user_id = users.id
WHERE messages.category_id=5 AND messages.parent_id=0
ORDER BY messages.id DESC LIMIT 30) ilv
ORDER BY id ASC
(这里是输出示例:http://lab.mirgorod.us/res.pdf)
是否可以在此查询中再添加一列:子消息计数(parent_id = 父消息的 id)?
【问题讨论】:
【参考方案1】:您可以使用子查询轻松完成:
SELECT * FROM
(SELECT messages.id as id,
messages.user_id,
messages.category_id,
messages.parent_id,
messages.message,
messages.create_date,
messages.update_date,
messages.status,
users.name as username,
users.id as userid,
users.email as useremail,
users.phone as userphone,
users.active as useractive,
users.role as userroel,
users.date as register_date,
(SELECT COUNT(*) FROM afo_messages WHERE parent_id=messages.id) AS `sub messages`
FROM `afo_messages` as messages
INNER JOIN `key_users` as users ON messages.user_id = users.id
WHERE messages.category_id=5 AND messages.parent_id=0
ORDER BY messages.id DESC LIMIT 30) ilv
ORDER BY id ASC
【讨论】:
但是如何处理我的查询呢? 只需添加以 (SELECT COUNT... 开头的行,仅此而已。它就像另一个字段。如果你想要我可以发布整个查询,我会缩短它。【参考方案2】:尝试将其添加为列:
child_count = (select count(*) from afo_messages where parent_id=messages.id)
【讨论】:
以上是关于在 SQL 中计算带有 where 子句的字段的主要内容,如果未能解决你的问题,请参考以下文章
按查询的where子句中的字段顺序对sql查询的结果进行排序
Django ORM 是不是在 sql where 子句中将已删除的字段映射到其他字段之前?
带有可选 Where 子句和 Sql Server CE 的 Linq
当您连接 2 个具有相同架构的表并检查除一个以外的所有字段是不是相等时,如何避免在 SQL 中编写冗长的 where 子句?