data_table信息
idx | type | value
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
4 | 4 | 4
查询
SELECT * FROM data_table WHERE idx IN (1, 1, 2, 1, 1, 3, 4, 4, 1);
我收到了当前的结果:
idx | type | value
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
4 | 4 | 4
但我打算收到以下结果:
idx | type | value
1 | 1 | 1
1 | 1 | 1
2 | 2 | 2
1 | 1 | 1
1 | 1 | 1
3 | 3 | 3
4 | 4 | 4
4 | 4 | 4
1 | 1 | 1
如何更改查询以获得所需结果?
答案 0 :(得分:0)
我害怕你应该用union all
写一些丑陋的sql:
select * from data_table where idx = 1
union all
select * from data_table where idx = 1
union all
select * from data_table where idx = 2
union all
select * from data_table where idx = 1
union all
select * from data_table where idx = 1
union all
select * from data_table where idx = 3
union all
select * from data_table where idx = 4
union all
select * from data_table where idx = 4
union all
select * from data_table where idx = 1
或类似的东西:
select data_table.*
from (
select 1 idx
union all select 1
union all select 1
union all select 2
union all select 1
union all select 1
union all select 3
union all select 4
union all select 4
union all select 1
) t
left join data_table
on t.idx = data_table.idx
注意: 第二种方式会让您获得不同的订单,并受到@Willem Van Onsem
的启发答案 1 :(得分:0)
解决此问题的一种潜在方法是动态创建表格,然后执行JOIN
:
CREATE TEMPORARY TABLE ids (id INT NOT NULL);
INSERT INTO ids VALUES (1), (1), (2), (1), (1), (3), (4), (4), (1);
SELECT data_table.* FROM
FROM ids JOIN data_table ON data_table.idx = ids.id;
DROP ids;
答案 2 :(得分:0)
如果您需要获取订购的行,您将硬编码的内容,那么您可以模拟其他列(在这种情况下为ord
),然后在ORDER BY
子句中使用此列:
SELECT data_table.* FROM data_table
inner join (
select 1 as idx, 1 as ord
union all
select 1 as idx, 2 as ord
union all
select 2 as idx, 3 as ord
union all
select 1 as idx, 4 as ord
union all
select 1 as idx, 5 as ord
union all
select 3 as idx, 6 as ord
union all
select 4 as idx, 7 as ord
union all
select 4 as idx, 8 as ord
union all
select 1 as idx, 9 as ord
) your_list
on
data_table.idx = your_list.idx
order by your_list.ord