简体   繁体   English

MySQL查询和重新排序结果

[英]Mysql query and reordering results

My SQL query is like this 我的SQL查询是这样的

SELECT `product_code`, `test`
FROM `table_products`
WHERE `product_code` IN ('38986', '222098', '1113426', '3645651', ...)

I would like the results to be ordered as in product_code order shown in query and also when there is no matching for that product_code in table, I would like to add an empty line in SQL result. 我希望结果按查询中显示的product_code顺序排序,并且当表中该product_code没有匹配项时,我想在SQL结果中添加一个空行。

There (probably) is no other way except that you express the values as rows: 除了将值表示为行之外,没有其他方法(可能):

SELECT codelist.code, table_products.whatever
FROM (
    SELECT 38986 AS code, 1 AS sort UNION ALL
    SELECT 222098,        2         UNION ALL
    SELECT 1113426,       3         UNION ALL
    SELECT 3645651,       4
) AS codelist
LEFT JOIN table_products ON codelist.code = table_products.product_code
ORDER BY codelist.sort

The LEFT JOIN will give you the code number and empty right hand side row if there is no match. 如果找不到匹配项,则LEFT JOIN将为您提供代码编号,并在右侧排空。 ORDER BY sort will sort the products in the desired order. ORDER BY sort将按所需顺序对产品进行排序。

You can have the reference product code values in another table and use right outer join 您可以在另一个表中使用参考产品代码值,并使用正确的外部联接

eg) 例如)

create table Test(id integer, title varchar(100));
create table ref(idtosee integer);//reference table
insert into ref(idtosee) values(1);
insert into ref(idtosee) values(4);
insert into Test(id, title) values(1, "Hello");
insert into Test(id, title) values(2, "sHello");


select id,title,idtosee from Test right outer join ref on id=idtosee;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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