MySQL - 查询以错误的顺序返回结果

时间:2016-07-22 08:44:04

标签: mysql

以下MySQL查询以不同的顺序返回结果,尽管" ORDER BY"对于两个查询都是相同的:

表格结构

+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| image_id        | int(10)     | NO   | PRI | NULL    | auto_increment |
| property_id     | int(10)     | NO   |     | 0       |                |
| image_title     | text        | NO   |     | NULL    |                |
| image_title_id  | int(10)     | NO   |     | 0       |                |
| image_index     | smallint(3) | NO   |     | 0       |                |
| image_version   | tinyint(1)  | NO   |     | 2       |                |
| image_landscape | tinyint(1)  | NO   |     | 1       |                |
| image_visible   | tinyint(1)  | NO   |     | 1       |                |
| image_type      | tinyint(1)  | NO   |     | 3       |                |
+-----------------+-------------+------+-----+---------+----------------+

TEST 1

查询:

SELECT image_id, room_text
FROM property_record_images
INNER JOIN property_data_rooms ON property_record_images.image_title_id = property_data_rooms.room_id
WHERE property_id = 1029
ORDER BY image_index

结果:

+----------+-----------------+
| image_id | room_text       |
+----------+-----------------+
|     2042 | Front elevation |
|     2043 | Garden to rear  |
|     2044 | Kitchen         |
|     2045 | Breakfast area  |
|     2046 | Lounge          |
|     2047 | Master bedroom  |
|     2048 | Studio          |
+----------+-----------------+

TEST 2

查询:

SELECT GROUP_CONCAT(CONCAT(property_record_images.image_id) SEPARATOR '|')
FROM property_record_images
INNER JOIN property ON property_record_images.property_id = property.property_id
WHERE property_record_images.property_id = 1029
ORDER BY image_index

结果:

+---------------------------------------------------------------------+
| GROUP_CONCAT(CONCAT(property_record_images.image_id) SEPARATOR '|') |
+---------------------------------------------------------------------+
| 2048|2047|2044|2045|2046|2043|2042                                  |
+---------------------------------------------------------------------+

这是随机记录(不同的" property_id")发生的,所以它不是简单的,只是为第二个查询倒转ORDER BY。

知道为什么会发生这种情况以及我的查询出错了吗?

1 个答案:

答案 0 :(得分:1)

请参阅http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

我认为你应该通过以下方式获得有序团队联合:

SELECT GROUP_CONCAT(CONCAT(property_record_images.image_id) ORDER BY image_index SEPARATOR '|')
FROM property_record_images
INNER JOIN property ON property_record_images.property_id = property.property_id
WHERE property_record_images.property_id = 1029
ORDER BY image_index