簡體   English   中英

同一張表上的兩個SUM()查詢,但使用不同的where子句

[英]Two SUM() Queries on the Same Table But Using Different Where Clauses

我猜想那里有一個簡單的解決方案,但是這讓我發瘋,試圖使其工作。 我想在同一個表上執行兩個SUM()查詢,但是它們都有不同的WHERE子句。

該表用於用戶投票系統,因此用戶可以對其他用戶內容進行投票。 我希望能夠列出當前用戶的活動(他們添加的內容/類別),並將其與有多少其他用戶對當前用戶內容投票的詳細信息結合起來。

本質上,我想從同一張表中合並下面的兩個查詢。

SELECT category_id,
SUM(content_add) AS content_add_count,
SUM(category_add) AS category_add_count
FROM table1 WHERE user_id = '" . $user_id . "' GROUP BY category_id


SELECT SUM(normal_vote) AS agree_votes
FROM table1
WHERE issued_by_user != '" . $user_id . "'
AND user_id = '" . $user_id . "'
AND plus = '1'
GROUP BY category_id

我已經嘗試將第二個查詢放在上面的第一個查詢中的另一個SUM()中,但這顯然無法在MySQL中完成,但這是我想盡可能實現的目標。

SELECT 
  category_id
  ,SUM(content_add) AS content_add_count
  ,SUM(category_add) AS category_add_count
  ,SUM(if(issued_by_user != '" . $user_id . "' AND plus = '1',normal_vote,0)) AS agree_votes
FROM table1 
WHERE user_id = '" . $user_id . "' 
GROUP BY category_id

暫無
暫無

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

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