0

表“计划”

id   name
1     abc
2     def
3     ghi

表“时间表”

id     fk_store     fk_plan
1         4            1
2         4            1
3         4            1
4         6            1
5         6            1
6         5            3
7         7            3
8         7            3
9         12           1

这是我的查询:

SELECT plan.id as id, name, 
(SELECT GROUP_CONCAT(cnt) cnt FROM (SELECT COUNT(*) cnt 
FROM schedule WHERE fk_plan = plan.id GROUP BY fk_store) q) as schedule_count  
FROM plan LEFT JOIN schedule ON plan.id = schedule.fk_plan GROUP BY plan.id

我期待这个结果(例如在数组中):

 [0] = array(
    ['id'] = 1,
    ['name'] = 'abc',
    ['schedule_count'] = '3, 2, 1'
 ),

 [1] = array(
    ['id'] = 2,
    ['name'] = 'def',     
    ['schedule_count'] = ''
),

 [2] = array(
    ['id'] = 3,
    ['name'] = 'ghi',     
    ['schedule_count'] = '2,1'
),

不幸的是,我收到一个错误,即 WHERE 子句中的 plan.id 列未定义。当我不使用 WHERE 时,每个数组中的结果 'schedule_count' 是 '3, 2, 2, 1, 1'。我找到了许多类似的解决方案,但我无法修复它。

我希望我的问题很清楚。先感谢您。

4

2 回答 2

2

尝试这个

    SELECT  plan.id, name ,  GROUP_CONCAT(cnt)  AS schedule_count
    FROM plan left join (select fk_plan, count(fk_store) as cnt from schedule 
                         GROUP BY fk_store)t
              ON t.fk_plan  = plan.id                                 
    GROUP BY plan.id  

小提琴演示

  • 如果你显示 0 而不是(null)然后用这个替换上面的 GROUP_CONCAT

    GROUP_CONCAT(if(cnt is null , 0 , cnt))
    
于 2013-07-04T12:10:23.967 回答
0

使用连接:-

SELECT plan.id as id, name, GROUP_CONCAT(PlanCnt)
FROM plan
LEFT OUTER JOIN (SELECT fk_plan, COUNT(DISTINCT fk_store) AS PlanCnt FROM schedule GROUP BY fk_plan) Sub1
ON plan.id = Sub1.fk_plan
GROUP BY plan.id as id, plan.name
于 2013-07-04T12:04:54.710 回答