2010-10-21 274 views
0

我的系統由兩種用戶類型組成 - 學生和導師。
- 導師可以創建類和包
- 學生和教師可以購買類和包Mysql查詢幫助

以下是表涉及

Groups
Users - 包含用戶類型
Tutor_Details的共同領域 - 導師特定字段
WebClasses - 由導師創建的類
Learning_Packs - 創建的包導師 Orders - 每一次購買記錄
Order_Details - 每購買多套的記錄 - 在購買
Payments

以下查詢將產生的所有用戶(學生和導師)的列表,並顯示3 fields-用戶儘可能多的項目名,orders - 購買和topics項目的數量 - 創建類和包總數 -

SELECT u.name, 
     COUNT(DISTINCT(o.id_order))           AS 
     orders, 
     ((COUNT(DISTINCT(wc.id_wc))) + (COUNT(DISTINCT(lp.id_lp)))) AS 
     topics 
FROM users AS u 
     LEFT JOIN tutor_details AS td 
     ON u.id_user = td.id_user 
     INNER JOIN groups AS g 
     ON u.id_group = g.id_group 
     LEFT JOIN webclasses AS wc 
     ON td.id_tutor = wc.id_author 
     LEFT JOIN learning_packs AS lp 
     ON td.id_tutor = lp.id_author 
     LEFT JOIN orders AS o 
     ON (u.id_user = o.id_user) 
     LEFT JOIN order_details AS od 
     ON (o.id_order = od.id_order) 
     LEFT JOIN payments AS p 
     ON (o.id_order = p.id_order) 
WHERE IF(o.id_order != 0, o.order_status = 'paid', 1) 
     AND IF(p.id_payment != 0, p.payment_status = 'success', 1) 
GROUP BY u.id_user 
ORDER BY u.id_user ASC 

幫助需要
現在,我想爲topics計數添加另一個過濾器/條件。只有那些主題應該計入wc.status = 1或lp.status = 1。我希望在單個查詢中做同樣的事情。請注意,由於查詢必須仍然顯示學生(未參加任何課程)和已採取id_status = 0級課程的導師,因此無法在主要塊內(組塊之前)添加條件。

topics計數應該只考慮類/包條件,這就是我想要的。查詢仍應顯示當前查詢顯示的所有用戶。

感謝,
Sandeepan

回答

0

好吧,我找到了自己的解決方案之前,任何人:)

SELECT u.id_user, 
     (Concat(u.name, ' ', u.surname))        AS name 
     , 
     u.login, 
     u.status, 
     u.email, 
     g.name               AS TYPE 
     , 
     u.joined, 
     COUNT(DISTINCT(o.id_order))          AS 
     orders, 
     (COUNT(DISTINCT(IF(wc.id_status = 1, wc.id_wc, NULL))) + 
      COUNT(DISTINCT(IF(lp.id_status = 1, lp.id_lp, NULL)))) AS 
     topics 
FROM users AS u 
     LEFT JOIN tutor_details AS td 
     ON u.id_user = td.id_user 
     INNER JOIN groups AS g 
     ON u.id_group = g.id_group 
     LEFT JOIN webclasses AS wc 
     ON td.id_tutor = wc.id_author 
     LEFT JOIN learning_packs AS lp 
     ON td.id_tutor = lp.id_author 
     LEFT JOIN orders AS o 
     ON (u.id_user = o.id_user) 
     LEFT JOIN order_details AS od 
     ON (o.id_order = od.id_order) 
     LEFT JOIN payments AS p 
     ON (o.id_order = p.id_order) 
WHERE IF(o.id_order != 0, o.order_status = 'paid', 1) 
     AND IF(p.id_payment != 0, p.payment_status = 'success', 1) 
GROUP BY u.id_user 
ORDER BY u.id_user ASC