简体   繁体   中英

Count same values in mysql query

So i have a query like

SELECT * FROM `catalog` WHERE `id` IN ('2','2','3','3','3');

And this return only 2 rows with id 2 and 3. It is possible make it return 5 rows (2 with id "2" and 3 with id "3") or add count as new column?

Not sure why you would want to do something like this, but instead of using an 'in' clause you could use an inner query:

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

Try something like this:

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

It can be done using temporary tables:

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);

if you need count

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM