這兩天項目裡出了一個問題,LIMIT使用後報錯。
需求是這樣的,我有3張表,infor信息表,mconfig物料配置表,maaply物料申請表,要求是讀出申請表中哪些人申請哪些物料
於是我先是這樣寫的:
復制代碼 代碼如下:
SELECT infor.name,infor.phone,infor.add,
mconfig.mname,mapply.acount,from_unixtime(mapply.atime,'%Y-%m-%d') as 'atime'
FROM mapply right JOIN infor ON mapply.uid = infor.uid inner JOIN mconfig ON mapply.mid = mconfig.mid
WHERE mapply.aid
IN (
SELECT aid
FROM `mapply` where state = $state
ORDER BY `atime` , `uid` DESC
LIMIT 0,10
)
結果報錯了
當時沒注意報的什麼錯誤,只是看到LIMIT什麼的錯誤,於是改了下代碼
復制代碼 代碼如下:
SELECT infor.name,infor.phone,infor.add,
mconfig.mname,mapply.acount,from_unixtime(mapply.atime,'%Y-%m-%d') as 'atime'
FROM mapply right JOIN infor ON mapply.uid = infor.uid inner JOIN mconfig ON mapply.mid = mconfig.mid
WHERE mapply.aid
IN (
SELECT aid
FROM `mapply` where state = $state
ORDER BY `atime` , `uid` DESC
)
<pre name="code" class="sql">LIMIT 0,10</pre>
這樣沒有報錯,莫離以為OK了,但是運行後發現,數據有問題
和單純的讀出申請表的內容不一樣,才發現LIMIT的位置放錯了,於是又把LIMIT發在IN裡,結果報錯如下
This version of MySQL doesn't yet support ‘LIMIT & IN/ALL/ANY/SOME subquery'
細看才知道,IN裡不支持LIMIT。那怎麼辦呢?
於是度娘後得知,在IN裡再使用一張臨時表,把需要的內容先查出來,
修改後代碼如下:
復制代碼 代碼如下:
SELECT infor.name,infor.phone,infor.add,
mconfig.mname,mapply.acount,from_unixtime(mapply.atime,'%Y-%m-%d') as 'atime'
FROM mapply right JOIN infor ON mapply.uid = infor.uid inner JOIN mconfig ON mapply.mid = mconfig.mid
WHERE mapply.aid
IN (
SELECT aid
FROM (SELECT `aid` FROM `mapply` where state = $state
ORDER BY `atime` , `uid` DESC
LIMIT 0,10)AS `tp`
)
運行後,問題解決~~~