簡體   English   中英

SQL條件查詢表

[英]Sql conditional query on table

我有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語句。 我不知道如何查詢和計算這些狀態。


多虧了小提琴,我設法創建了這個查詢,但是出現一個錯誤:請注意,( 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` 

您可以將sum()與expression一起使用以根據您的條件獲取計數,使用sum中的expression將得到布爾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

小提琴演示

編輯在原始查詢您不使用回蜱正確

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` 

可能是這樣的:

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

不是最漂亮的,但它可以工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM