子查询选择归档

时间:2013-01-07 12:09:00

标签: mysql sql subquery

我尝试在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中尝试过。

提前致谢!

4 个答案:

答案 0 :(得分:2)

,之后你错过了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

答案 1 :(得分:1)

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

使用','在每一栏之后

答案 2 :(得分:1)

为了避免这些错误(比如缺少逗号),我喜欢这样写出查询......

    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;

答案 3 :(得分:0)

使用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