Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

SQL/mariadb Select with IN() over mutiple columns in the same order

I need a syntax in sql which returns a result in the same order as given in the IN() field. The problem is that the primary key consists of two keys.

So the following does not apply:

SELECT * FROM table where id IN (4,5,6) ORDER BY FIELD (id,4,5,6);

my table:

primary(column 1+2)   column 3   column 4   cloumn 5......
    hash | num      |          |          |

Pseudo code for understanding would look like this:

SELECT * FROM table WHERE (hash,num) IN (["fjdigjhu",5],["fgfjhgaa",2],...) ORDER BY FIELD ([hash,num],["fjdigjhu",5],["fgfjhgaa",2],...); 
question from:https://stackoverflow.com/questions/65844269/sql-mariadb-select-with-in-over-mutiple-columns-in-the-same-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest a derived table:

SELECT t.*
FROM table t JOIN
     (SELECT 1 as ord, 'fjdigjhu' as hash, 5 as num UNION ALL
      SELECT 2 as ord, 'fgfjhgaa' as hash, 5 as num UNION ALL
      . . . 
     ) x
     USING (hash, num)
ORDER BY x.ord;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...