MySQL查询中的IF语句

时间:2014-02-18 07:54:55

标签: mysql if-statement

我需要帮助。我有这个问题:

SELECT IF(book_id=2, 'NTR', if(book_id=5,'CBC', if(book_id=1,'CBC','Repair')) AS   
'STATUS',
COUNT(IF(book_id=2, 'NTR', if(book_id=5,'CBC', if(book_id=1,'CBC','Repair'))) AS 
'TOTAL'
FROM book_entry AS b
WHERE last_updated=(SELECT last_updated FROM book_entry WHERE book_code=b.book_code ORDER  
BY last_updated DESC) AND (SELECT description FROM book_categori AS c, book_item AS i  
WHERE c.id=i.id AND i_item_code=b.item_code) = "NOVEL" 
GROUP BY IF(book_id=2, 'NTR', if(book_id=5,'CBC', if(book_id=1,'CBC','Repair')))

此表的总数据为128.实际上,有超过3个状态但我只想获得3个状态(NTR,CBC和其他状态我将其分组为1状态,我将其设置为'修复') 。从我上面创建的查询中,我得到了这个结果:

STATUS      TOTAL
---------------
CBC         70
Repair      58

这不是我想要的结果。我想要的是这样的:

STATUS      TOTAL
-----------------
CBC         70
Repair      58
NTR         0

实际上'NTR'没有id,这意味着id = 2实际上是null,但我想把它包含在上面的结果中。

任何人都可以教我在查询中需要更改的内容以获得该结果吗?

1 个答案:

答案 0 :(得分:0)

看起来你想要一个状态表 - 包含status_id int,status varchar

的字段

添加CBC,NTR和修复记录

然后将status_id的列添加到book_entry并根据需要进行更新

然后您的查询可以加入状态表 - 例如:

select status.status, count(*) total
from status left join book_entry 
on status.status_id = book_entry.status_id
join book_categori 
on book_entry.item_code = book_categori.i_item_code
where book_categori.description = 'NOVEL'
group by status.status

(无法弄清楚你要用where子句的第一部分做什么

last_updated=(SELECT last_updated FROM book_entry WHERE book_code=b.book_code 
ORDER BY last_updated DESC) 

除了让查询更难阅读之外,我认为它不会有任何影响。