我遇到了问题并且已经有一些类似的问题,但它们并没有解决我的问题。
我有几家酒店和图片。图片以数字排序。我想要所有酒店和数字最少的图片。
当我尝试跟踪查询时,我得到正确的顺序:
SELECT s25.entry_id AS id,
s25.value AS title,
s35.file AS picture,
s86.value AS picture_sort
FROM sym_entries_data_25 AS s25
LEFT JOIN sym_entries_data_34 AS s34 ON (s25.entry_id = s34.relation_id)
LEFT JOIN sym_entries_data_35 AS s35 ON (s34.entry_id = s35.entry_id)
LEFT JOIN sym_entries_data_86 AS s86 ON (s34.entry_id = s86.entry_id)
ORDER BY s86.value
我将获得数组
[0] => Array
(
[id] => 243
[title] => Hotel
[picture] => louis2.jpg
[picture_sort] => 1
)
[1] => Array
(
[id] => 243
[title] => Hotel
[picture] => louis1.jpg
[picture_sort] => 2
)
[2] => Array
(
[id] => 243
[title] => Hotel
[picture] => louis3.jpg
[picture_sort] => 3
)
......等等
但我每个酒店只想要一个结果,所以我尝试了一个GROUP BY:
SELECT s25.entry_id AS id,
s25.value AS title,
s35.file AS picture,
s86.value AS picture_sort
FROM sym_entries_data_25 AS s25
LEFT JOIN sym_entries_data_34 AS s34 ON (s25.entry_id = s34.relation_id)
LEFT JOIN sym_entries_data_35 AS s35 ON (s34.entry_id = s35.entry_id)
LEFT JOIN sym_entries_data_86 AS s86 ON (s34.entry_id = s86.entry_id)
GROUP BY s25.value
ORDER BY s86.value
然后我只得到一个结果但是一个随机结果,而不是第一个结果:
[0] => Array
(
[id] => 243
[title] => Hotel
[picture] => louis3.jpg
[picture_sort] => 3
)
这可能是什么问题?
答案 0 :(得分:1)
当您执行group by
时,您无法保证您未分组的列的值。
例如,如果您有一个包含列a和b的表,以及如下数据:
a | b
-----
1 | 2
1 | 3
如果您执行select * from table group by a
,则可以获得2或3作为b的值。
如果您只想要酒店的最高结果,您需要做的不是分组,而是将picture_sort等于min(picture_sort)