Sam Provides
Sam Provides

Reputation: 259

Mysql query and reordering results

My SQL query is like this

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.

Upvotes: 0

Views: 38

Answers (2)

bright rajesh
bright rajesh

Reputation: 41

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;

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272106

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. ORDER BY sort will sort the products in the desired order.

Upvotes: 1

Related Questions