我有以下查询:
SELECT a.topicID, d.catalogFileID, d.catalogFileExtension, a.sortorder
FROM catalog_topics a
LEFT JOIN catalog_files_join b ON a.catalogID = b.foreignKey
LEFT JOIN catalog_files_join c ON c.foreignKey = b.catalogFileID
LEFT JOIN catalog_files d ON d.catalogFileID = b.catalogFileID
WHERE b.fileTypeID = 'gvl401'
AND c.fileTypeID = 'gvl25'
AND a.topicid = 'top340'
取出:
topicID catalogFileID catalogFileExtension sortorder
top340 cfil1070 jpg 5
top340 cfil958 jpg 7
top340 cfil958 jpg 7
top340 cfil956 jpg 6
top340 cfil864 jpg 4
top340 cfil862 jpg 3
但是我不想回到多行,而是想获得一行(最小排序顺序)。所以在这种情况下是最后一行。
我尝试了以下查询:
SELECT a.topicID, d.catalogFileID, d.catalogFileExtension, min( a.sortorder )
AS smallestorder
FROM catalog_topics a
LEFT JOIN catalog_files_join b ON a.catalogID = b.foreignKey
LEFT JOIN catalog_files_join c ON c.foreignKey = b.catalogFileID
LEFT JOIN catalog_files d ON d.catalogFileID = b.catalogFileID
WHERE b.fileTypeID = 'gvl401'
AND c.fileTypeID = 'gvl25'
AND a.topicid = 'top340'
GROUP BY a.topicid
取出:
topicID catalogFileID catalogFileExtension smallestorder
top340 cfil1070 jpg 3
那是错的。即使我得到了最小的排序顺序......我没有得到与之对应的行。
如果通过将第一个查询的结果存储在一个单独的表中来更容易解决这个问题,那么我也会对此持开放态度。
答案 0 :(得分:2)
SELECT ... ORDER BY a.sortorder LIMIT 1
答案 1 :(得分:1)
您可以使用ORDER BY和LIMIT代替GROUP BY:
SELECT a.topicID, d.catalogFileID, d.catalogFileExtension, a.sortorder
FROM catalog_topics a
LEFT JOIN catalog_files_join b ON a.catalogID = b.foreignKey
LEFT JOIN catalog_files_join c ON c.foreignKey = b.catalogFileID
LEFT JOIN catalog_files d ON d.catalogFileID = b.catalogFileID
WHERE b.fileTypeID = 'gvl401'
AND c.fileTypeID = 'gvl25'
AND a.topicid = 'top340'
ORDER BY a.sortorder ASC
LIMIT 1