“无法在全局ORDER子句中使用”与mysql排序

时间:2012-03-16 08:21:20

标签: mysql

我对此SQL查询有疑问:

(SELECT tb1.id,tb1.bdate,tb1.jumpCard,tb1.publicImage,tb1.lastlogin
FROM users AS tb1, online AS tb2
WHERE tb1.valid='1' AND tb1.sex='female' AND tb1.looking_for='male' AND tb1.id = tb2.member_id
ORDER BY tb1.publicImage) ORDER BY tb1.id DESC

由于某些原因我得到了:

Table 'tb1' from one of the SELECTs cannot be used in global ORDER clause

任何建议?

由于

3 个答案:

答案 0 :(得分:10)

它不起作用的原因是外部ORDER BY无法“看到”tb1 - 它会看到内部子查询的结果。因此,在语法正确的查询版本中,您只需ORDER BY id

(SELECT tb1.id,tb1.bdate,tb1.jumpCard,tb1.publicImage,tb1.lastlogin
FROM users AS tb1, online AS tb2
WHERE tb1.valid='1' AND tb1.sex='female' AND tb1.looking_for='male' AND tb1.id = tb2.member_id
ORDER BY tb1.publicImage) ORDER BY id DESC

但是,正如其他人指出的那样,这可以更简单地写成由id

排序的单个查询

答案 1 :(得分:3)

如果在select周围加上括号,那么内部表格将不会在

之外显示
SELECT tb1.id,tb1.bdate,tb1.jumpCard,tb1.publicImage,tb1.lastlogin
FROM users AS tb1, online AS tb2
WHERE tb1.valid='1' AND tb1.sex='female' AND tb1.looking_for='male' AND tb1.id = tb2.member_id
ORDER BY tb1.publicImage, tb1.id DESC

您可以在一个order by子句中指定多个列

答案 2 :(得分:2)

在select语句后关闭括号时,第二个order by子句将失效。而是尝试在单个order by语句中按列合并您的订单,如下所示:

SELECT tb1.id,tb1.bdate,tb1.jumpCard,tb1.publicImage,tb1.lastlogin
FROM users AS tb1, online AS tb2
WHERE tb1.valid='1' AND tb1.sex='female' AND tb1.looking_for='male' AND tb1.id = tb2.member_id
ORDER BY tb1.publicImage, tb1.id DESC