mysql计数带有条件的子表行

时间:2009-05-06 20:48:04

标签: mysql count conditional left-join

我有两张桌子:“用户” - > “命令”

表:用户

user_id
-----------
    u1
    u2

表:订单

order_id | user_id | flag
-------------------------
    o1   |    u1   |  fA
    o2   |    u2   |  fB

Y需要获取所有用户计算带有标记'fA'的订单的次数

结果我需要什么:

user_id | orders
----------------
   u1   |   1
   u2   |   0

我尝试:

SELECT
    u.user_id,
    COUNT(o.order_id) AS orders
FROM
    `user` AS u LEFT JOIN
    `order` AS o USING (user_id)
WHERE
    o.flag IS NULL OR
    o.flag IN ('fA')
GROUP BY
    u.user_id;

但是,此查询不包括 user = u2 ,因为他没有带有标记 fA 的订单; 我需要用户= u2 订单= 0

也许是这样的:

SELECT
    u.user_id,
    COUNT(o.order_id IF o.flag IN('fA')) OR 0 AS count ...

表格和数据:

CREATE TABLE `user` (user_id VARCHAR(2) NULL);
CREATE TABLE `order` (order_id VARCHAR(2) NULL,user_id VARCHAR(2) NULL,flag VARCHAR(2) NULL);
INSERT INTO `user` VALUES ('u1'), ('u2');
INSERT INTO `order` VALUES ('o1','u1','fA'),('o2','u2','fB');

5 个答案:

答案 0 :(得分:4)

您需要使用左外连接而不是左连接

SELECT
    u.user_id,
    COUNT(o.order_id) AS orders
FROM
    `user` AS u LEFT OUTER JOIN
    `order` AS o USING (user_id)
WHERE
    o.flag IS NULL OR
    o.flag IN ('fA')
GROUP BY
    u.user_id;

答案 1 :(得分:3)

您可以尝试使用'LEFT JOIN'的'ON'语句中的条件,如下所示:

SELECT u.user_id, COUNT(o.user_id)
FROM user u
LEFT JOIN `order` o ON u.user_id = o.user_id AND o.flag = 'fA'
GROUP BY user_id

Runing example in SQLFiddle

答案 2 :(得分:1)

您可以尝试使用CASE语句。我今天没有MYSQL所以我可以验证语法,但它应该接近这个:

  SELECT   u.user_id,
             CASE
                WHEN (SELECT COUNT (*)
                        FROM ORDER z
                       WHERE z.user_id = USER.user_id) > 0
                   THEN COUNT (*)
                ELSE 0
             END CASE AS cnt
        FROM USER
    GROUP BY USER.user_id;

答案 3 :(得分:1)

此查询将起作用:

SELECT
    u.user_id,
    COUNT(o.order_id) AS orders
FROM
    `user` AS u LEFT OUTER JOIN
    (SELECT user_id, order_id FROM `order` WHERE flag IS NULL OR flag IN ('fA')) as o
    USING (user_id)
GROUP BY
    u.user_id;

答案 4 :(得分:1)

至少有三种方法可以做到:

  1. 只需使用依赖子查询即可。

    SELECT u.user_id, (SELECT count(user_id) FROM `order` o WHERE o.user_id = u.user_id AND o.flag = 'fA') count
    FROM `user` u;
    
  2. 在子查询上使用LEFT JOIN

    SELECT u.user_id, count(o.user_id) count
    FROM `user` u
    LEFT JOIN (SELECT user_id FROM `order` WHERE flag = 'fA') o USING (user_id)
    GROUP BY u.user_id;
    
  3. 在组合条件下使用LEFT JOIN

    SELECT u.user_id, count(o.user_id) count
    FROM `user` u
    LEFT JOIN `order` o ON o.user_id = u.user_id AND o.flag = 'fA'
    GROUP BY u.user_id;
    

我认为最快的是最后一个,但是需要在足够大的数据上进行测试并查看执行计划。

SQL Fiddle