简体   繁体   English

两个查询返回不同的结果

[英]Two queries returned different result

I have a problem with SQL queries. 我对SQL查询有问题。 I have two nearly identical queries that differ just that the first one returns only one column, id , and the second one returns all columns, * . 我有两个几乎相同的查询,不同之处在于第一个查询仅返回一个列id ,第二个查询返回所有列* Queries are as follows: 查询如下:

Query 1: 查询1:

SELECT id 
FROM `import_data` 
WHERE 1 AND parent IS NULL 
ORDER BY CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, "")) DESC;

Query 2: 查询2:

SELECT * 
FROM `import_data` 
WHERE 1 AND parent IS NULL 
ORDER BY CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, "")) DESC;

Each query has a different order of results, even though I have specified the same ORDER BY . 即使我指定了相同的ORDER BY ,每个查询的结果顺序也不同。

You would get different orders if you have multiple rows where CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, "")) are the same. 如果您有多个行,其中CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, ""))相同CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, ""))则会得到不同的订单。

How does SQL order rows where the key values are the same? 在键值相同的情况下,SQL如何排序行? The answer is that the ordering is arbitrary and can change from one query to the next. 答案是排序是任意的,并且可以从一个查询更改为下一个查询。 SQL does not guarantee stable sorts, meaning that the order of the final sort, when there are ties, is indeterminate. SQL 保证稳定的排序,这意味着最终的排序顺序,当有关系,是不确定的。

I would suggest that you just add id to the order by clause: 我建议您只将id添加到order by子句:

ORDER BY CONCAT(category_1, COALESCE(category_2, ""), COALESCE(category_3, "")) DESC, id

If id is unique, then the two queries will return the same order. 如果id是唯一的,则两个查询将返回相同的顺序。

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

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