我试图在 MySQL selct 语句中进行子选择,例如如下所示:
SELECT
c.id AS id,
c.name AS name,
(SELECT count(*) FROM orders o WHERE o.user_id = c.id) AS order_count
FROM
customers c
任何想法为什么这在 MySQL 中不起作用?是否可以在 MySQL 中做类似的事情?在版本 3.23.58 和 5.1.60 中尝试过。
提前致谢!
你错过了,
之后name
,试试这个:
SELECT
c.id AS id,
c.name AS name,
(SELECT count(*) FROM orders o WHERE o.user_id = c.id) AS order_count
FROM
customers c
为了避免这些类型的错误(比如缺少逗号),我喜欢这样写查询......
SELECT c.id
, c.name
, COALESCE(COUNT(o.user_id),0) order_count
FROM customers c
LEFT
JOIN orders o
ON o.user_id = c.id
GROUP
BY c.id;
SELECT
c.id AS id ,
c.name AS name ,
(SELECT count(*)
FROM orders o
WHERE o.user_id = c.id) AS order_count
FROM
customers c
在每列之后使用“,”
另一种方法使用joins
样本数据:
ID NAME
1 john
2 jack
3 kelly
ID USERID
10 1
11 2
12 1
13 3
14 2
15 3
16 2
17 4
18 1
询问:
SELECT count(o.userid), c.id, c.name
FROM cusomter c
LEFT JOIN orders o
ON c.id = o.userid
GROUP BY c.id
;
case when
如果客户没有任何订单,您可以添加将 null 表示为 0。你的选择。
结果:
COUNT(O.USERID) ID NAME
3 1 john
3 2 jack
2 3 kelly