所以我的问题是我正在尝试对多个表中的列使用ORDER BY,多个表始终是同一表。
我的SQL语句:
SELECT
n0.val AS n312,
n1.val AS n309,
c.food_name,
f.name,
FROM contents n0, contents n1, contents c
LEFT JOIN foods f ON f.id = c.food_id
WHERE n0.url = c.url AND n0.orig_source_id = 312 AND n1.url = c.url AND n1.orig_source_id = 309
GROUP BY c.food_name
ORDER BY n312 DESC, n309 DESC
LIMIT 30
问题是这里只订购n312,而不订购n309,它们都应该订购吗?我认为这是查询中多个表的问题,但不确定如何解决此问题。这些值都是小数点。
感谢您的任何帮助。
答案 0 :(得分:1)
这按预期工作。 ORDER BY
首先使用列n312
对表进行排序,然后再使用列n309
对表进行排序。假设您有一个如下表:
n312 | n309
-----------
2.0 | 1.0
5.0 | 2.0
2.0 | 3.0
3.0 | 2.0
5.0 | 1.0
然后,“ ORDER BY”将按以下方式排列您的桌子:
n312 | n309
-----------
5.0 | 2.0
5.0 | 1.0
3.0 | 2.0
2.0 | 3.0
2.0 | 1.0
它首先按n312
对行进行排序。如果对于两行n312
具有相同的值(例如,行1和行2),则它将按列n309
的值对它们进行排序。
如果您想要类似的东西:
n312 | n309
-----------
5.0 | 3.0
5.0 | 2.0
3.0 | 2.0
2.0 | 1.0
2.0 | 1.0
然后您必须执行类似以下的操作:
SELECT t1.n312, t2.n309 from
(select row_number() as id, n312 from t ORDER BY n312) as t1
JOIN
(select row_number() as id, n309 from t ORDER BY n309) as t2
WHERE t1.id = t2.id;
想法是先用两个列分别对表排序,然后选择排序的列。
答案 1 :(得分:0)
是的,我认为应该可以...
尝试一下:
SELECT * FROM (
SELECT n0.val AS n312, n1.val AS n309, c.food_name, f.name,
FROM contents n0, contents n1, contents c
LEFT JOIN foods f
ON f.id = c.food_id
WHERE n0.url = c.url
AND n0.orig_source_id = 312
AND n1.url = c.url
AND n1.orig_source_id = 309
GROUP BY c.food_name
ORDER BY n312 DESC, n309 DESC
LIMIT 30
) ORDER BY n312 DESC, n309 DESC