2013-12-20 37 views
2

我想加入3個表如何加入3代表對這些情況

 
Table employer: 
+-------------+-------------+---------+ 
| employer_id | position_id | shop_id | 
+-------------+-------------+---------+ 
|  1  |  2  | 2 | 
|  2  |  2  | 2 | 
|  3  |  2  | 2 | 
|  4  |  1  | 1 | 
|  5  |  1  | 2 | 
+-------------+-------------+---------+ 

Table position: 
+-------------+-----------------+ 
| position_id | position_name | 
+-------------+-----------------+ 
|  1  | Receptionist | 
|  2  | Secretary  | 
+-------------+-----------------+ 

Table shop: 
+---------+-----------+ 
| shop_id | shop_name | 
+---------+-----------+ 
| 1 | Shop ABC | 
| 2 | Shop DEF | 
+---------+-----------+ 

這裏是我的查詢:

SELECT S.*, P.*, E.*, COUNT(E.employer_id) AS NumberOfJobs FROM ((shop AS S INNER JOIN employer AS E ON S.shop_id=E.shop_id) INNER JOIN position AS P ON P.position_id=E.position_id) GROUP BY S.shop_id; 

結果我得到:

 
Shop ABC 
    Receptionist Job Available : 1 

Shop DEF 
    Secretary  Job Available : 4 

但什麼我想要的是:

 
Shop ABC 
    Receptionist Job Available : 1 

Shop DEF 
    Receptionist Job Available : 1  
    Secretary  Job Available : 3 

什麼是正確的查詢來獲得我想要的結果?感謝有人能幫助我解決這個問題。非常感謝你!

回答

1

你需要按商店和位置,而不僅僅是開店:

SELECT S._Id , S.Shop_Name 
     P.Position_Name , 
     COUNT(E.employer_id) AS NumberOfJobs 
FROM shop AS S 
INNER JOIN employer AS E ON S.shop_id = E.shop_id 
INNER JOIN position AS P ON P.position_id = E.position_id 

GROUP BY S.shop_id, S.Shop_Name, P.Position_Name 
+0

謝謝您的答覆。我試過你的查詢,「Shop DEF」會顯示兩次。如何只顯示一個「Shop DEF」? – user3121472

+0

你正在混淆數據庫查詢中的用戶界面。該查詢將爲您提供所有需要呈現給用戶的信息,您的用戶界面應以您想要的格式顯示它 – Greg