自定义子选择请求和where子句与MySQL

时间:2014-10-21 12:29:10

标签: mysql

我尝试使用子选择列出表的内容,并仅选择与我的WHERE子句匹配的表:

SELECT DISTINCT `torrentItem` as ti,
(SELECT COUNT(*) FROM votes WHERE `torrentItem` = ti AND `voteType` = 0) AS `badVotes`, 
(SELECT COUNT(*) FROM votes WHERE `torrentItem` = ti AND `voteType` = 1) AS `goodVotes`,
(SELECT TIMESTAMPDIFF(WEEK,(SELECT MAX(`date`) FROM votes WHERE `torrentItem` = ti),CURRENT_TIMESTAMP)) AS `weeksSinceLastVote`
FROM `votes` 
WHERE (`badVotes` > 1 AND `goodVotes` = 0 AND `weeksSinceLastVote` > 1);

它无效:MySQL告诉我,我不能在badVotes子句中使用goodVotesWHEREError Code: 1054. Unknown column 'badVotes' in 'where clause'

你能解释一下为什么吗?怎么做?

2 个答案:

答案 0 :(得分:1)

对于表中的每一行,都会执行每个子查询。表演噩梦:)
您可以将查询重写为

SELECT `torrentItem` as ti,
SUM(`voteType` = 0) AS `badVotes`, 
SUM(`voteType` = 1) AS `goodVotes`,
TIMESTAMPDIFF(WEEK, MAX(`date`), CURRENT_TIMESTAMP) AS `weeksSinceLastVote`
FROM `votes` 
GROUP BY ti
HAVING (`badVotes` > 1 AND `goodVotes` = 0 AND `weeksSinceLastVote` > 1);

这将比你的子查询运行得更好,更好。

您无法在where子句中使用别名的原因是解释查询的顺序。

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. ORDER BY
  6. 选择

答案 1 :(得分:1)

您不能在where子句中使用列别名。

但是你可以使用having子句。

在此处查看更多详情http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html