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_name
,final_price
,avg_rate
和count_comment
在result_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
你要麼需要重複你用來計算final_price邏輯在WHERE子句或使用具有替代的位置。 –