了解MySQL逻辑

时间:2017-08-08 12:23:17

标签: mysql sql

这是一段MySQL代码,它运行在其中一个网站的背景中。

我想了解new列的含义。 任何有单个订单的客户都会被标记为new = 1吗?

代码如下所示:

select
a.id_order,
IF((
        SELECT so.id_order 
        FROM `orders` so 
        WHERE so.id_customer = a.id_customer 
        AND 
        so.id_order < a.id_order 
        LIMIT 1) > 0, 0, 1) as new               // new keyword

        FROM `orders` a 

        LEFT JOIN `customer` c ON 
       (c.`id_customer` = a.`id_customer`)

2 个答案:

答案 0 :(得分:0)

首先,让我假设id_order永远不会为负或零。

如果客户的订单ID较小,则查询返回“0”。目的是标记第一个订单。

如果客户只有一个订单,则其值始终为1,因为子查询将返回NULL

我会写逻辑:

SELECT o.id_order,
       (NOT EXISTS (SELECT 1
                    FROM orders so
                    WHERE so.id_customer = o.id_customer AND
                          so.id_order < o.id_order
                   )
       ) as is_first_order
FROM orders o LEFT JOIN
     customer c
     ON c.id_customer = o.id_customer;

如果所有订单都有客户,则LEFT JOIN应该是不必要的。事实上,JOIN根本不是必需的,你可以使用:

select o.id_order,
       (NOT EXISTS (SELECT 1
                    FROM orders so
                    WHERE so.id_customer = o.id_customer AND
                          so.id_order < o.id_order
                   )
       ) as is_first_order
FROM orders o ;

答案 1 :(得分:0)

“new”这里是括号

之间if语句的列结果的名称
((
        SELECT so.id_order 
        FROM `orders` so 
        WHERE so.id_customer = a.id_customer 
        AND 
        so.id_order < a.id_order 
        LIMIT 1) > 0, 0, 1) 

如果

(SELECT so.id_order 
FROM `orders` so 
WHERE so.id_customer = a.id_customer 
AND so.id_order < a.id_order 
LIMIT 1) 

大于0则“新”列值将为0 否则它将是1