我已经编写了一个sql查询来获取产品现在我想在我的查询中应用where子句但是我在哪里有条件
if stock = 'in':
where will be num>0:
if stock = 'out':
where will be num = 0;
if stock = ' ':
no where clause will apply
我写这个有两个条件
where
case
when stock='in' then num_in_stock > 0
when stock ='out' then num_in_stock = 0
end;
但它不起作用。我收到一个错误:
(1064,“您的SQL语法有错误;请查看手册 对应于您的MySQL服务器版本,以便使用正确的语法 靠近';作为a.partner_id = 5的地方 由a.date_updat'在第20行订购“) 我通过
获得库变量
stock = request.GET.get('stock')
我的完整查询是
SELECT distinct a.product_id, a.variant_id
from
(
SELECT cp.id as variant_id,
COALESCE(cp.parent_id,cp.id) as product_id,
ps.partner_id as partner_id,
ps.price_retail as price_retail,
COALESCE(oc.order_count,0) as order_count,
cp.date_updated as date_updated
FROM partner_stockrecord as ps
LEFT JOIN catalogue_product as cp on cp.id = ps.product_id
LEFT JOIN (
select product_id,count(product_id) as order_count
from order_line group by product_id) as oc on oc.product_id = ps.id
where ((''' + stock +''') = 'in' and num_in_stock > 0 ) or
((''' + stock +''') = 'out' and num_in_stock = 0 );
)
as a where a.partner_id = '''+ str(partner_obj.id) +''' order by a.date_updated desc;
''');
答案 0 :(得分:5)
转换:
where
case
when stock='in' then num_in_stock > 0
when stock ='out' then num_in_stock = 0
end
成:
where (stock = 'in' and num_in_stock > 0 ) or
(stock = 'out' and num_in_stock = 0 )
CASE
是表达式,它只返回一个标量值。它不能用于控制SQL中的执行流程。