2

我有三个这样的表:

漫画

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

小伙子

|   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

4

3 回答 3

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 
于 2012-08-12T13:27:39.683 回答
1

你是left JOIN故意用的吗?你知道它是如何工作的吗?使用它两次使您的选择在 16 行结果表上运行。尝试首先选择所有结果 (*),然后修复您的FROM子句以返回要从中选择的所需数据。

从您的评论来看,您似乎建议使用Inner join

于 2012-08-12T13:23:09.917 回答
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'

左连接返回重复的行。

于 2012-08-12T14:40:17.503 回答