2017-05-16 86 views
-1

我有以下SQL查詢:SQL子查詢:行中找不到

SELECT t1.`userID`,`name`, COUNT(*) AS `count`, (SELECT `val` FROM `user-data` WHERE `userID` = t1.userID AND `keyID` = 2 LIMIT 1) AS `staff` 
FROM `activity` t1 
LEFT JOIN `users` ON `users`.`id` = t1.`userID` 
WHERE 
t1.`userID` <> 0 
GROUP BY t1.`userID` 
ORDER BY `count` DESC LIMIT 10 

其中一期工程,它需要大約2秒。但是,我想找個地方staff <> 1條目:

SELECT t1.`userID`,`name`, COUNT(*) AS `count`, (SELECT `val` FROM `user-data` WHERE `userID` = t1.userID AND `keyID` = 2 LIMIT 1) AS `staff` 
FROM `activity` t1 
LEFT JOIN `users` ON `users`.`id` = t1.`userID` 
WHERE 
t1.`userID` <> 0 
AND `staff` <> 1 
GROUP BY t1.`userID` 
ORDER BY `count` DESC LIMIT 10 

我得到的錯誤:Unknown column 'staff' in 'where clause'

我可以把子查詢的WHERE子句中,但隨後的查詢需要70秒。

但我當然應該可以訪問我在SELECT語句中引用的列嗎?

+1

'和staff' <'是不完整的 –

+0

只是檢查,你忘了在你的查詢中添加AND'staff' <> 1? – lloiacono

+0

不,你不應該。選擇列表在** where子句後處理**。 – Shadow

回答

2

由於選擇列表是在where子句之後處理的,因此不能通過其別名引用where子句中的任何計算字段。

您可以將子查詢移入加入,只要它返回一個只記錄,即使沒有限制條款:

SELECT t1.`userID`,`name`, COUNT(*) AS `count`, `user-data`.`val` as staff 
FROM `activity` t1 
LEFT JOIN `users` ON `users`.`id` = t1.`userID` 
LEFT JOIN `user-data` ON `user-data`.`userID`=t1.userID AND `user-data`.`keyID` = 2 
WHERE 
    t1.`userID` <> 0 
    AND `user-data`.`val` <> 1 
GROUP BY t1.`userID`, `user-data`.`val` 
ORDER BY `count` DESC 
LIMIT 10 
+0

謝謝你,完美的工作! – Chud37

+0

@Strawberry:我知道員工的價值來自哪裏,它在子查詢中有所描述。從子查詢中,還可以推導出如何在沒有模式的情況下將表連接在一起。如果破壞你的評論值得贊成,那就這樣吧。 – Shadow