如果你要测试条件,并根据条件成立与否,返回不同值,用if函数
1,if函数,
如果是真的则返回first,是假的就返回second,
案例,如果订单是今年的就定义为active,之前的就是archived。之间的方法是写两段select然后union,这里我们用if
use sql_store;
select
order_id,
order_date,
if(year(order_date)=year(now()),
'active',
'archived')
from orders
2,练习:写查询
答案:
use sql_store;
select
product_id,
name,
count(*)as orders,
if(count(*)>1,
'many times',
'once') as frequency
from products
join order_items using(product_id)
group by
product_id,
name