我尝试使用子选择列出表的内容,并仅选择与我的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
子句中使用goodVotes
或WHERE
:
Error Code: 1054. Unknown column 'badVotes' in 'where clause'
答案 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 :(得分:1)
您不能在where子句中使用列别名。
但是你可以使用having
子句。
在此处查看更多详情http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html