[英]how can I write IF statement in mysql
I have a table with type
field. 我有一个
type
字段的表。
how can I check this field in query: 如何在查询中检查此字段:
I want to check it if type
== 'a' 如果
type
=='a',我想检查一下
then bes
= amount
, bed
= '-' 然后
bes
= amount
, bed
=' - '
ELSE bed
= amount
, bes
= '-' ELSE
bed
= amount
, bes
=' - '
bes and bed is not really exists in my table but amount is (int) bes和bed在我的表中并不存在但是数量是(int)
this is my try: 这是我的尝试:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount AS bes, '-' AS bed ELSE billing.amount AS bed, '-' AS bes END
FROM billing
... my searches wasn't useful ...我的搜索无用
any solution... 解决方案......
You can create condition for every row, MySQL
supports inline IF
statements. 您可以为每一行创建条件,
MySQL
支持内联 IF
语句。
SELECT billing.*,
IF(billing.type = 'A', billing.amount, '-') AS bes,
IF(billing.type = 'A', '-', billing.amount) AS bed
FROM billing
You'll need two case statements for that: 你需要两个案例陈述:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' AS bes END,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount AS bed END
FROM billing
One CASE-WHEN-THEN-ELSE
can have only one return value... 一个
CASE-WHEN-THEN-ELSE
只能有一个返回值......
This should do the trick: 这应该做的伎俩:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' END AS bes,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount END AS bed
FROM billing
SELECT billing.*,
CASE WHEN billing.type = 'A' THEN billing.amount ELSE 0 END AS bes,
CASE WHEN billing.type <> 'A' THEN billing.amount ELSE 0 END AS bed
FROM billing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.