2016-11-12 94 views
2

我有一个查询如下,返回所有要求的数据。然后在我需要写的下一个查询中,我需要限制输出到子查询大于5的位置。MySQL别名子查询不能用在where子句中

我将显示示例,但我无法理解为什么我无法执行所尝试的操作。

查询不受限制

select t1.BOOK_NUM, t1.BOOK_TITLE, 
(select count(t2.CHECK_OUT_DATE) 
from checkout t2 
where t2.BOOK_NUM = t1.BOOK_NUM) as Times_Checked_Out 
from book t1 
order by Times_Checked_Out desc, t1.BOOK_TITLE; 

输出的屏幕截图 enter image description here

尝试在与限制查询

select t1.BOOK_NUM, t1.BOOK_TITLE, 
(select count(t2.CHECK_OUT_DATE) 
from checkout t2 
where t2.BOOK_NUM = t1.BOOK_NUM) as Times_Checked_Out 
from book t1 
where Times_Checked_Out > 5 
order by Times_Checked_Out desc, t1.BOOK_TITLE; 

错误 enter image description here

回答

4

你不能在where子句中使用派生列,需要使用HAVING

select t1.BOOK_NUM, t1.BOOK_TITLE, 
(select count(t2.CHECK_OUT_DATE) 
from checkout t2 
where t2.BOOK_NUM = t1.BOOK_NUM) as Times_Checked_Out 
from book t1 
HAVING Times_Checked_Out > 5 
order by Times_Checked_Out desc, t1.BOOK_TITLE; 
+0

非常感谢你,当时间到了,我会标记为答案。 –

+0

你也可以帮我理解这一点,我有截图中的输出,而不是列标题是Times_Checked_Out我想要检查出时间,但是当我使用'文本'时,我没有得到任何结果。 –