简体   繁体   中英

mysql “where in” automatic distinct?

I am a bit lost. Here is my query:

SELECT id, title FROM products WHERE id IN (4,2,6,4,2);

The query will result in 3 records only.

How can I get all 5 records (in this case I do want to see the duplicates).

Many thanks.

Update: Sorry for not being exact enough. Thanks for the comments, indeed I didn't understand the "IN" correctly.

This is my data:

---------------------
|  id |  title      |
---------------------
|  2  |  product_2  |
---------------------
|  4  |  product_4  |
---------------------
|  6  |  product_6  |
---------------------

My intention is to receive the following data since I have a list of ids:

---------------------
|  id |  title      |
---------------------
|  4  |  product_4  |
---------------------
|  2  |  product_2  |
---------------------
|  6  |  product_6  |
---------------------
|  4  |  product_4  |
---------------------
|  2  |  product_2  |
---------------------

So I have a list of ids and want to receive the title of the product. Ideally even the order should be preserved.

I think you have a problem with the concept of In

Let's suppose you have a simply table with this values

id
--
1
2
3
4
5

if you do

select id from simplyTable where id in (2,3,4,2,3,4)

you will get

id
2
3
4

That's becuase IN statement in where is a filter, to decide to show or not a row. If you put repeated values, SQL will ignore that, because when finds the first value, and checks the match, it will show the row, and won't keep checking against the other values So, you need to put once time each number, and if you put it repeated, it won't show them more times.

If you need to repeated some values, a way to do this is Use UNION ALL

select id from simplyTable where id in (2,3,4)
union all
select id from simplyTable where id in (2,3,4)

this will return you:

id
2
3
4
2
3
4

don't use UNION only because it will apply a distinct, and will return you only one time each value. UNION will let you show the values repeated, because you're showintg results of querys i one result, and I think that's what you're expecting.

In this case, your query will be:

SELECT id, title FROM products WHERE id IN (4,2,6);
UNION ALL
SELECT id, title FROM products WHERE id IN (4,2)

Join with Temporary Table

SqlFiddle :

DROP   TABLE IF EXISTS num;
CREATE TABLE num (i INT);    
INSERT INTO  num (i) VALUES (4),(2),(6),(4),(2);

SELECT id, title
FROM   num, products
WHERE  id = i;

Inspired by another answer .

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