在mysql查询中计算相同的值

时间:2012-10-27 22:10:24

标签: mysql

所以我有一个像

这样的查询
SELECT * FROM `catalog` WHERE `id` IN ('2','2','3','3','3');

这只返回2行,ID为2和3.有可能使其返回5行(2为id“2”,3为id为“3”)或将计数添加为新列?

3 个答案:

答案 0 :(得分:1)

不确定为什么要这样做,但不是使用'in'子句,而是使用内部查询:

select *
from `catalog` c,
(
    select 2 ids
    union all
    select 2
    union all
    select 3
    union all
    select 3
    union all
    select 3
) k
where c.id = k.ids

答案 1 :(得分:1)

尝试这样的事情:

SELECT t.p,count(*)  FROM 
    catalog, 
    (SELECT 2 as id
    Union all select 2 as id
    Union all select 3 as id
    Union all select 3 as id
    Union all select 3 as id)as t 
where catalog.id = t.id

答案 2 :(得分:0)

可以使用临时表来完成:

create temporary table arrayt (id int);
insert into arrayt values  ('2'),('2'),('3'),('3'),('3');
select catalog.* from arrayt a LEFT JOIN catalog on (a.id=catalog.id);

如果你需要数量

select count(catalog.id) as count,catalog.id as id from arrayt a LEFT JOIN catalog on (a.id=catalog.id) group by catalog.id;