2014-03-29 80 views
0
SELECT B.*, SC.cate_name, (
     CASE WHEN special_offer_type ='Fixed Value' 
     THEN B.price - special_offer 
     WHEN special_offer_type = 'Discount %' 
     THEN B.price * (1 - special_offer/100.0) 
     ELSE B.price 
     END 
     ) AS final_price, 
(IFNULL(xx.avg_rate,'0')) AS avg_rate, 
(IFNULL(yy.count_comment, '0')) AS count_comment 
FROM book B JOIN setting_category SC ON B.cate_id = SC.cate_id 
LEFT JOIN (SELECT a.isbn, sum(a.rate)/count(a.rate) AS avg_rate 
FROM book_rating a 
GROUP BY a.isbn) AS xx ON b.isbn = xx.isbn 
LEFT JOIN (SELECT c.isbn, count(*) AS count_comment FROM book_comment c 
GROUP BY c.isbn) AS yy ON b.isbn = yy.isbn 

上述编码中使用未知列,我添加4列cate_namefinal_priceavg_ratecount_commentresult_table(THX戈登·利诺夫,罗纳德亚历山大Kailola)MySQL的:在where子句

用户AAA和BBB加入评级书001,所以书001的avg_rate为(4 + 5)/ 2 = 4.5

用户XXX YYY和添加的注释书001,所以书的count_comment 001 = 2

现在,我想查询final_price范围末尾添加下面的代码。

WHERE final_price BETWEEN '60' AND '100' ORDER BY final_price

但是,我得到一个错误#1054 - Unknown column 'final_price' in 'where clause' 我怎样才能解决呢?和任何建议来简化代码?

book 
-----------------------------------------------------------      
isbn cate_id price special_offer special_offer_type 
001 1   125  5    Fixed Value 
002 1   90  30    Discount % 
003 2   150  50    Fixed Value 

setting_category 
--------------------        
cate_id cate_name 
1   Fiction 
2   Dictionary 

book_rating        
------------------------------------------ 
user dateadd  timeadd isbn rate 
AAA 2014/03/20 15:00:00 001  4 
BBB 2014/03/21 15:00:00 001  5 
CCC 2014/03/22 15:00:00 002  2 

book_comment 
---------------------------------------------- 
user dateadd  timeadd isbn comment 
XXX  2014/03/20 16:00:00 001 good 
YYY  2014/03/21 16:00:00 001 great 

result_table 
----------------------------------------------------------------------------------------------------------------- 
isbn cate_id price special_offer special_offer_type cate_name final_price avg_rate count_comment 
001 1   125  5    Fixed Value   Fiction  120   4.5  2 
002 1   90  30    Discount %   Fiction  63   2   0 
003 2   150  50    Fixed Value   Dictionary 100   0   0 
+0

你要么需要重复你用来计算final_price逻辑在WHERE子句或使用具有替代的位置。 –

回答

0

嵌入having子句是这样的:

-- include other part of your query here 
FROM book B JOIN setting_category SC ON B.cate_id = SC.cate_id 
LEFT JOIN (SELECT a.isbn, sum(a.rate)/count(a.rate) AS avg_rate 
      FROM book_rating a 
      GROUP BY a.isbn) AS xx ON b.isbn = xx.isbn 
LEFT JOIN (SELECT c.isbn, count(*) AS count_comment FROM book_comment c 
      GROUP BY c.isbn) AS yy ON b.isbn = yy.isbn 

-- having clause start 
HAVING final_price BETWEEN '60' AND '100' 
-- having end 

ORDER BY final_price