5

我有以下mysql查询:

SELECT id, sum(views) as total_views
FROM table
WHERE id IN (1,2,3)
GROUP BY id
ORDER BY total_views ASC

如果只id 1,3在数据库中找到,我仍然想id 2出现,total_views设置为 0。

有没有办法做到这一点?这不能使用任何其他表。

4

6 回答 6

7

该查询使用由联合组成的子查询对可能的 ID 列表进行硬编码……然后将这组 id 连接到包含要计数的信息的表中。

即使没有出现,这也会在您的结果中保留一个 ID:

SELECT ids.id, sum(views) as total_views
FROM (
    SELECT 1 AS ID 
    UNION ALL SELECT 2 AS ID 
    UNION ALL SELECT 3 AS ID 
) ids 
LEFT JOIN table
    ON table.ID = ids.ID
GROUP BY ids.id
ORDER BY total_views ASC

或者,如果您有一个numbers 表,您可以执行以下查询:

SELECT numbers.number, sum(views) as total_views
FROM
    numbers
    LEFT JOIN table
        ON table.ID = ids.ID
WHERE numbers.number IN (1, 2, 3)
GROUP BY numbers.number
ORDER BY total_views ASC
于 2012-11-20T22:43:46.313 回答
3

这是 Micheal 解决方案的替代方案(请注意,这不是一个糟糕的解决方案——即使有“很多”ID),只要您不针对集群进行查询。

create temporary table __ids (
  id int unsigned primary key
) engine=MEMORY;

insert into __ids (id) values
  (1),
  (2),
  (3)
;

SELECT table.id, sum(views) as total_views
FROM __ids left join table using (id)
GROUP BY table.id
ORDER BY total_views ASC

如果您的查询变得复杂,我什至可以设想它以这种方式运行更有效。但是,如果我是你,我会将此选项与 Michael 使用真实数据的临时 UNION 表选项进行基准测试。

于 2012-11-27T23:21:48.740 回答
1

在@Michael 的回答中,如果您确实有一个包含您关心的ID 的表格,您可以将其用作“ID”来代替Michael 的内联数据。

于 2012-11-20T22:51:22.827 回答
0

检查这个小提琴...... http://www.sqlfiddle.com/#!2/a9392/3

Select B.ID, sum(A.views) sum from tableB B
 left outer join tableA A
 on B.ID = A.ID
group by A.ID

还要检查 http://www.sqlfiddle.com/#!2/a1bb7/1

于 2012-11-20T23:05:43.333 回答
0

试试这个

    SELECT id 
                (CASE 1
                    IF EXISTS THEN  views = mytable.views END
                    IF NOT EXIST THEN views = 0 END
                CASE 2
                    IF EXISTS THEN  views = mytable.views END
                    IF NOT EXIST THEN views = 0 END
                CASE 3
                    IF EXISTS THEN  views = mytable.views END
                    IF NOT EXIST THEN views = 0 END), sum(views) as total_views
    FROM mytable
    WHERE id IN (1,2,3)
    GROUP BY id
    ORDER BY total_views ASC
于 2012-12-03T11:13:14.710 回答
0

它必须是行还是您可以旋转数据以为每个 id 提供一行和一列?

SELECT
  SUM(IF (id=1, views, 0)) views_1,
  SUM(IF (id=2, views, 0)) views_2,
  SUM(IF (id=3, views, 0)) views_3
FROM table
于 2012-12-03T22:18:18.287 回答