我是mysql的新手....它可能看起来转储问题....但我已经尝试了3个小时...这里我想做什么....
SELECT
MERCHANT_ID,
IFNULL(COUNT(SUBSCRIBE_ID),0)
FROM SUBSCRIBE_TABLE
WHERE
MERCHANT_ID IS NULL OR
MERCHANT_ID IN(1000000000066,1000000000104,1000000000103,1000000000105)
GROUP BY MERCHANT_ID
ORDER BY
FIND_IN_SET(MERCHANT_ID,'1000000000066,1000000000104,1000000000103,1000000000105');
AND输出是......
+------------------+---------------------------------+
| MERCHANT_ID | IFNULL(COUNT(SUBSCRIBE_ID),0) |
+------------------+---------------------------------+
| 1000000000066 | 2 |
| 1000000000103 | 1 |
+------------------+---------------------------------+
但我期待以下方式...
+------------------+---------------------------------+
| MERCHANT_ID | IFNULL(COUNT(SUBSCRIBE_ID),0) |
+------------------+---------------------------------+
| 1000000000066 | 2 |
| 1000000000104 | 0 |
| 1000000000103 | 1 |
| 1000000000105 | 0 |
+------------------+---------------------------------+
我尝试添加MERCHANT_ID IS NULL
...但无法获得默认值的结果...... :(
答案 0 :(得分:1)
您只会获得实际位于SUBSCRIBE_TABLE
的记录。如果要获取所有id的记录,则必须首先使用这些值“创建临时表”(或使用带UNION
的子查询),然后将结果加入其中。
您的查询可能如下所示:
SELECT
merchant_id,
COUNT(subscribe_id)
FROM
(SELECT 1000000000066 AS merchant_id, 1 AS SortKey
UNION ALL
SELECT 1000000000104 AS merchant_id, 2 AS SortKey
UNION ALL
SELECT 1000000000103 AS merchant_id, 3 AS SortKey
UNION ALL
SELECT 1000000000105 AS merchant_id, 4 AS SortKey
) AS temp
LEFT JOIN subscribe_table USING (merchant_id)
GROUP BY merchant_id
ORDER BY SortKey ASC
我将您的FIND_IN_SET
替换为子查询中的列SortKey
。 COUNT
只计算非空行,如果没有找到则返回0。你不需要围绕它IFNULL
。
如果你有超过4 merchant_id
个,你可能想要用临时表做同样的事情。请看这里的例子:
Mysql: Create inline table within select statement?