我有 2 个表。
我正在尝试从 articles
中获取所有列
- 状态数,其中 status = 0 为 status0
- 状态数,其中 status = 1 为 status1
“从文章中获取所有内容,对于每个文章行,获取 status = 0 的评论数作为 status0,并获取 status = 1 的评论数作为 status1”。可能吗?
表格:
articles
========
id name
---------
1 abc
2 def
3 ghi
comments
========
id article_id status
-------------------------
1 2 1
2 2 0
3 1 0
4 3 1
文章结合状态数的预期结果:
id name status0 status1
------------------------------
1 abc 1 0
2 def 1 1
3 ghi 0 1
我正在使用 Laravel 的 Eloquent,但足以查看原始 sql 语句。我不知道如何查询和统计这些状态。
多亏了 fiddle,我成功地创建了这个查询,但是我得到了一个错误:请注意 (articles = db_surveys
and comments = db_answers
)
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`status=1) status1` from `db_surveys` left join `db_answers` on `db_surveys`.`i' at line 1 (SQL: select `db_surveys`.`*, SUM(db_answers`.`status=0) status0, SUM(db_answers`.`status=1) status1` from `db_surveys` left join `db_answers` on `db_surveys`.`id` = `db_answers`.`surveyid` where `db_surveys`.`userid` = 6oGxr)"
完整查询:
"select `db_surveys`.`*, SUM(db_answers`.`status=0) status0, SUM(db_answers`.`status=1) status1` from `db_surveys` left join `db_answers` on `db_surveys`.`id` = `db_answers`.`surveyid` where `db_surveys`.`userid` = 123 group by `db_surveys`.`id`"
**
最终查询:
**
SELECT
`s`.*,
SUM(`a`.`status`='pending') `status0`,
SUM(`a`.`status`='confirmed') `status1`
FROM
`db_surveys` s
LEFT JOIN `db_answers` a
ON `s`.`id` = `a`.`surveyid`
WHERE `s`.`userid` = '6oGxr'
GROUP BY `s`.`id`
最佳答案
您可以使用 sum() 和表达式来根据您的条件获取计数,在 sum 中使用表达式将得到 bool 值 o 或 1
SELECT a.*
,SUM(`status` =0) status0
,SUM(`status` =1) status1
FROM articles a
LEFT JOIN comments c ON(a.id = c.article_id)
GROUP BY a.id
Fiddle Demo
编辑 在您的原始查询中,您没有正确使用反引号
SELECT
`s`.*,
SUM(`a`.`status`=0) `status0`,
SUM(`a`.`status`=1) `status1`
FROM
`db_surveys` s
LEFT JOIN `db_answers` a
ON `s`.`id` = `a`.`surveyid`
WHERE `s`.`userid` = 123
GROUP BY `s`.`id`
关于php - 对表的sql条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23364759/