表上的sql条件查询

时间:2014-04-29 12:31:26

标签: php mysql sql laravel

我有2张桌子。

我想从articles获取所有列 - 以及status0状态= 0的状态数 - 以及状态数= 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语句。我不知道如何查询和统计这些状态。


感谢小提琴我设法创建了这个查询,但是我收到了一个错误:请注意(articles = db_surveyscomments = 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` 

3 个答案:

答案 0 :(得分:2)

你可以使用sum()和expression来根据你的条件得到计数,使用sum中的表达式将得到boolean 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` 

答案 1 :(得分:0)

可能是这样的:

SELECT a.*, COUNT(c.*) AS status0, COUNT(c2.*) AS status1
FROM articles AS a
LEFT JOIN comments AS c ON c.article_id = a.id AND c.status = 0
LEFT JOIN comments AS c2 ON c.article_id = a.id AND c.status = 1

答案 2 :(得分:-1)

不是最漂亮的,但它有效:

SELECT articles.id, articles.name, 
     (SELECT COUNT(*) FROM comments WHERE article_id = articles.id AND status = 0), 
     (SELECT COUNT(*) FROM comments WHERE article_id = articles.id AND status = 1) 
FROM articles;

http://sqlfiddle.com/#!2/123b68/4