我有一個訪問數據庫中的幾個表:選擇查詢加入兩個字段?
ID | LocationName
1 | Location1
2 | Location2
ID | LocationID | Date | NumProductsDelivered
1 | 1 | 12/10 | 3
2 | 1 | 01/11 | 2
3 | 1 | 02/11 | 2
4 | 2 | 11/10 | 1
5 | 2 | 12/10 | 1
ID | LocationID | Date | NumEmployees | EmployeeType
1 | 1 | 12/10 | 10 | 1 (=Permanent)
2 | 1 | 12/10 | 3 | 2 (=Temporary)
3 | 1 | 12/10 | 1 | 3 (=Support)
4 | 2 | 10/10 | 1 | 1
5 | 2 | 11/10 | 2 | 1
6 | 2 | 11/10 | 1 | 2
7 | 2 | 11/10 | 1 | 3
8 | 2 | 12/10 | 2 | 1
9 | 2 | 12/10 | 1 | 3
我想要做的就是在LocationID作爲參數傳遞,並取回東西如下表等。所以,如果我在2傳我的LocationID,我應該得到:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
看起來這應該是一個非常簡單的查詢。我甚至不需要第一個表格,除非填寫用戶選擇他們想要報告的位置的表單上的組合框。不幸的是,我所做的一切都讓我得到了比我應得的更多的數據。我的困惑在於如何設置連接(大概是我在這裏尋找的),因爲我希望date和locationID對結果集中的每一行都是相同的。
任何幫助將不勝感激。
謝謝。
編輯: 好 - 答案下面也不太工作,但它確實讓我在正確的軌道上,我能夠使用以下查詢:
SELECT t1.Date, t2.NumProductsDelivered,
(SELECT t1a.NumEmployees
FROM table3 t1a
WHERE t1a.EmployeeType=1 AND t1a.LocationID=t1.LocationID AND t1a.Date= t1.Date)
AS "PermEmps",
(SELECT t1b.NumEmployees
FROM table3 t1b
WHERE t1b.EmployeeType=3 AND t1b.LocationID=t1.LocationID AND t1b.Date=t1.Date)
AS "SupportEmps"
FROM table3 AS t1 LEFT JOIN table2 AS t2 ON (t2.Date=t1.Date)
AND (t2.LocationID=t1.LocationID)
WHERE t1.LocationID=2
GROUP BY t1.Date, t1.LocationID, t2.NumProductsDelivered;
這讓我我正在尋找的結果。但是,如果產品交付地點有中斷,我看不到正確的結果。看起來,只要有空行,記錄就會停下來,然後再從頭回來。所以,在這裏我可能會看到這一點:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
01/10 | 2 | | 1
06/10 | 1 | |
我只看到這一點:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
01/10 | 2 | | 1
你不應該GROUP BY t1.LocationID因爲你沒有選擇它,它始終是2。我也要推薦使用比「t1」更好的名字來表示可讀性。另一個問題是一個謎題...... t1和t2之間是否存在1對1的關係?另外,嘗試刪除join和subselect以查看是否全部獲取您需要的日期(我會在下面添加到我的答案中) – 2010-04-30 20:04:29