skip to Main Content

I am unable to retrieve rows with repeated IDs using SELECT IN

ID column is Primary key with auto increment.

SELECT ID FROM dbproduct WHERE ID IN (3,2,1,4,3,2,1,4);

I get the following result back

 ID
-----
  1
  2
  3
  4
------

Other than that it doesnt seem to be displaying result in the order it was sent.

Im looking for a query to get the desired result is this

 ID
-----
  3
  2
  1
  4
  3
  2
  1
  4
------

cpsrvd 11.86.0.27

Database client version: libmysql – 5.6.43

PHP version: 7.3.6

2

Answers


  1. You can put these numbers in a derived table first (along with their sequence in the list), then join:

    select p.*
    from (
        select 3 id, 1 seq
        union all select 1, 2
        union all select 1, 3
        union all select 4, 4
        union all select 3, 5
        union all select 2, 6
        union all select 1, 7
        union all select 4, 8
    ) n
    inner join dbproduct p on p.id = n.id
    order by n.seq
    
    Login or Signup to reply.
  2. You can update mysql to Ver 8.0.21. It’s work.

    test

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search