order by与部分并集

wwodge7n  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(258)

很长一段时间以来,我一直使用这个方法来排序我的列表(对于html选择):

SELECT '' AS ID, '' AS Name UNION 
SELECT ID, Name FROM (SELECT ID, Name FROM myTable ORDER BY Name) AS myTableTmp

但在更新到新的mysql(mariadb)版本后,我发现这种排序不再有效。如本文所述,它与sql标准相冲突:mysql-order by inside子查询
获得所需订单的最佳实践是什么?或者我应该用简单的方法,加上 LIMIT 65000 要嵌套查询吗?
编辑:
嗯,我最初的例子不够精确,所以人们会误解我。下面是一个正确的例子:

CREATE TABLE IF NOT EXISTS `myTable` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(120) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

INSERT INTO `myTable` (`ID`, `Name`) VALUES
(1, 'Banana'),
(2, 'Apple'),
(3, NULL);

如果我在旧版本中选择:

SELECT '0' AS ID, '-' AS Name UNION 
SELECT ID, Name FROM (SELECT ID, Name FROM myTable ORDER BY Name) AS myTableTmp

我得到:

0   -
3   NULL
2   Apple
1   Banana

如何在新的mysql版本中获得相同的结果?

inn6fuwd

inn6fuwd1#

你可以用 ORDER BY CASE ... END 更改默认排序行为以获得预期结果。
工作原理
所有的“-”值都在order by中获得位置“1”
所有空值在order by中获得位置“2”
所有的名字都排在“3+”的位置,按字母表排序。
查询

SELECT '0' AS ID, '-' AS Name UNION 
SELECT ID, Name FROM (
  SELECT
     ID
   , Name
  FROM
   myTable
) AS myTableTmp
ORDER BY
 CASE 
  WHEN 
   Name = '-'
  THEN
   1
  WHEN 
   Name IS NULL
  THEN
   2
  ELSE 
   Name
 END

请参见演示https://www.db-fiddle.com/f/xcy45suedkn9gjhnpvqohd/2
但如果有人在表中加上“-”怎么办?如果那样的话,我可能会弄错身份证。。。
查询

SELECT
   '0' AS ID
 , '-' AS Name
 , 0 AS position

UNION

SELECT
   ID
 , Name
 , CASE
     WHEN 
      Name IS NULL
     THEN 
      2
     ELSE
      3
   END AS position
FROM (
   SELECT
       ID
     , Name
   FROM
    myTable 
) AS myTableTmp

ORDER BY 
   position
 , name ASC

请参见演示https://www.db-fiddle.com/f/xcy45suedkn9gjhnpvqohd/7

uwopmtnx

uwopmtnx2#

或者您可以通过外部移动订单:

SELECT 
    ID, Name
FROM
    (SELECT '' AS ID, '' AS Name UNION SELECT 
        ID, Name
    FROM
        yourTable) AS yourTableTmp
ORDER BY Name;
yks3o0rb

yks3o0rb3#

我想,目前最干净的纯sql解决方案就是在mysql中使用union和order by子句

SELECT ID, Name FROM (
SELECT '0' AS ID, '-' AS Name, 1 AS Rank UNION 
SELECT ID, Name, 2 AS Rank FROM myTable
) AS myTableTmp ORDER BY Rank, Name

相关问题