【问题标题】:Mysql query and reordering resultsMysql查询和重新排序结果
【发布时间】:2019-02-14 14:31:03
【问题描述】:

我的SQL查询是这样的

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

我希望按照查询中显示的 product_code 顺序对结果进行排序,并且当表中该 product_code 没有匹配时,我想在 SQL 结果中添加一个空行。

【问题讨论】:

  • "当表中没有匹配到该product_code时,我想在sql结果中添加一个空行。"为什么?
  • 我假设您的意思是如果产品代码222098 实际上不存在,您希望在结果集中返回一个空白行!对吗?
  • 我需要导出数据并匹配到一个csv文件

标签: mysql sql sql-order-by where-in


【解决方案1】:

除了将值表示为行之外(可能)没有其他方法:

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

LEFT JOIN 将为您提供代码编号,如果不匹配,则右侧为空行。 ORDER BY sort 将按所需顺序对产品进行排序。

【讨论】:

    【解决方案2】:

    您可以在另一个表中拥有参考产品代码值并使用右外连接

    例如)

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-15
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2012-05-10
      • 2014-08-22
      相关资源
      最近更新 更多