我有三张这样的表:
漫画
| 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 :(得分: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 :(得分:1)
您是否故意使用left JOIN
?你知道吗works怎么样?
使用它两次使您的选择运行在16行结果表上。
首先尝试选择所有结果(*),然后修复FROM
子句以返回所需的数据以供选择。
根据您的评论,您似乎可以使用Inner join。
答案 2 :(得分: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
如果您运行,您将在原始查询中看到问题:
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'
左连接返回重复的行。