2012-03-16 53 views
6

我有這個SQL查詢的問題:「無法在全球ORDER子句中使用」 與MySQL訂購

(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 

什麼建議嗎?

感謝

回答

8

它不工作的原因是外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下令

+0

你已經保存單個查詢我的生活 – 2016-12-02 18:22:47

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

指定多個列的選擇語句後的圓括號,您的第二個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