mysql - 如何在sql查询中应用if else

标签 mysql

我已经编写了一个 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, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; as a where a.partner_id = 5 order by a.date_updat' at line 20") I am getting stock variable by

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;
    ''');

最佳答案

转换:

 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 中的执行流程。

关于mysql - 如何在sql查询中应用if else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635564/

相关文章:

mysql - Eloquent 查询,可能的 Join

mysql - 如何编写这个复杂的 SQL 查询?

mysql - "Uncaught Error: Received packet in the wrong sequence"关闭 devtools - Electron + MySQL Node 驱动程序 + Webpack

php - "Commands out of sync; you can' t 现在运行此命令“同时在 PHP 中使用storedproc

mysql - 如何存储元数据数据类型

php - SQL : Get Number of First Place Scores of User

mysql - 增加Mysql自增值

mysql - 在 MySQL 中对 JSON 字段进行全文搜索

javascript - 保存带有散列标记的文本(Javascript - PHP - MySQL)

mysql - 返回 2 个表中相同 ID 的结果