SQL子查询:找不到列

时间:2017-05-16 09:10:53

标签: mysql

我有以下SQL查询:

$.ajax({
  url: '${pageContext.request.contextPath}/admin/sendMsg',
  method: 'POST',
  traditional: true,
  data: {
    driverList: drivers,
    constList: constIds,
    content: content
  },
  success: function(data) {
    if (data == "FAIL") {
      alert("File not found!");
    } 
  },
  error: function(request, status, error) {
    alert("The request failed: " + request.responseText);
  }
});

哪个有效,大约需要2秒钟。但我希望找到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

的条目
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

我可以将子查询放在WHERE子句中,但查询需要70秒。

但我肯定能够访问SELECT语句中的列引用吗?

1 个答案:

答案 0 :(得分:2)

Since the select list is processed after the where clause, you cannot reference any calculated field in the where clause via its alias.

You can move the subquery into a join, provided it returns a single record only even if there is no limit clause:

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