2012-08-12 51 views
2

我有三個表是這樣的:在一個查詢中多計

漫畫

| id | sendby 
------------------ 
| 1 | 1 
| 2 | 1 
| 3 | 1 
| 4 | 1 

chaprer

| id | sendby | translator | graphic 
------------------------------------------- 
| 1 | 1  | admin | other 
| 2 | 1  | admin | other 
| 3 | 1  | admin | admin 
| 4 | 1  | other | admin 

用戶

| userid | username 
----------------------- 
|  1 | admin  

我想算什麼我曾發過,但結果不正確。

我曾嘗試下面的查詢:

SELECT username, 
    SUM(
     CASE WHEN m.sendby = u.userid 
     THEN 1 ELSE 0 END 
    ) AS manga, 
    SUM(
     CASE WHEN c.sendby = u.userid 
     THEN 1 ELSE 0 END 
    ) AS chapter, 
    SUM(
     CASE WHEN c.translator = u.username 
     THEN 1 ELSE 0 END 
    ) AS translator, 
    SUM(
     CASE WHEN c.graphic = u.username 
     THEN 1 ELSE 0 END 
    ) AS graphic 
FROM user u 
    left JOIN manga m 
     ON m.sendby = u.userid 
    left JOIN chapter c 
     ON c.sendby = u.userid 
where u.userid = '1' 

但它返回此這是不正確的:

漫畫:16, 章:16, 譯者:12, 圖文:8

+0

你想要的結果是什麼? – 2012-08-12 13:17:34

+0

這是:漫畫:4,章節:4,翻譯:3,圖形:2 – kamal 2012-08-12 13:19:05

回答

2

下面是該

select 
    m.id, 
    count(m.sendby) as Manga, 
    lc.Chapter, 
    rc.Translater, 
    c.Grafix 
from manga as m 
    left join (select sendby, count(sendby) as Chapter from chaprer) as lc on lc.sendby = m.sendby 
    left join (select sendby, count(translater) as Translater from chaprer where translater = 'admin') as rc on rc.sendby = m.sendby 
    left join (select sendby, count(graphics) as Grafix from chaprer where translater = 'admin') as c on c.sendby = m.sendby 

查詢編輯
我已經測試此查詢,這取這個結果

Query Result 
id Manga Chapter Translater Grafix 
1 4  4  3   3 
1

您有意使用left JOIN嗎?你知道嗎works? 使用它兩次使您在16行結果表上進行選擇運行。 嘗試先選擇所有結果(*),然後修復您的FROM子句以返回所需的數據以供選擇。

從您的評論,看來你要使用Inner join

0

一個直接的辦法是做這樣的事情:

SELECT username, 
(SELECT COUNT(m.sendby) FROM manga m WHERE m.sendby= u.userid) AS manga, 
(SELECT COUNT(c.sendby) FROM chapter c WHERE c.sendby= u.userid) AS chapter, 
(SELECT COUNT(t.sendby) FROM chapter t WHERE t.translator= u.username) AS translator, 
(SELECT COUNT(g.sendby) FROM chapter g WHERE g.graphic= u.username) AS graphic 
FROM USER u 
WHERE userid=1 

您會在y中看到問題我們原來的查詢是否運行:

SELECT * 
FROM USER u 
    LEFT JOIN manga m 
     ON m.sendby = u.userid 
    LEFT JOIN chapter c 
     ON c.sendby = u.userid 
WHERE u.userid = '1' 

左連接返回重複行。

+0

這是依賴查詢,將採取更多的執行時間,然後離開連接查詢 – 2012-08-12 17:55:01

+0

對不起,但我不會推薦這種方法。運行4個不同的查詢不是SQL最佳實踐... – 2012-08-13 07:20:54

+0

這真的取決於。 OP是基於1個userid查詢的,這種方法非常好。 – 2012-08-13 11:39:01