子查询返回错误的答案

时间:2019-09-08 19:25:50

标签: mysql subquery

我有两个桌子 1:-用户

id  name
1   vivek
2   raj
3   mohan
4   gagan
5   priya

2:-购买

id  typee        user_id
1   class        1
2   class        1
3   course       1
4   class        2
5   test_series  3
6   test_series  2 

我正在尝试运行

select p.id,(select count(purchasee.user_id) as tot
             from purchasee
             where purchasee.user_id=p.id
             and typee='class'
             or typee='course' ) as classcourse,(select count(purchasee.user_id) as tot
                                                 from purchasee
                                                 where purchasee.user_id=p.id 
                                                 and typee='test_series') as test 
from purchasee as p
GROUP by p.user_id

查询及其助我一臂之力

id      Classcourse    test
1       3              0
4       1              0
5       0              1

预期答案是

id      Classcourse    test
1       3              0
4       1              1
5       0              1

我要选择用户购买(班级或课程)或(test_series),如果是,则购买课程或课程,然后对其进行计数,或者如果用户购买test_series,然后计算行数

1 个答案:

答案 0 :(得分:0)

尝试使用sql

SELECT p.id,
     SUM( IF( typeee = 'class' || typeee = 'course', 1,0) ) as tot,
     SUM( IF (typeee = 'test_series', 1,0) ) as classcourse
FROM purchasee as p
GROUP by p.user_id