2016-01-13 63 views
1

我有兩個表:我不能讓我的期望的SQL結果

業主

+----+------+------------+ 
| id | name | birth_year | 
+----+------+------------+ 
| 1 | John |  1970 | 
| 2 | Jane |  1980 | 
| 3 | Jack |  1990 | 
| 4 | Josh |  2000 | 
+----+------+------------+ 

Buylog

+----+----------+------------+ 
| id | owner_id | date | 
+----+----------+------------+ 
| 1 |  1 | 01/01/2016 | 
| 2 |  2 | 01/02/2016 | 
| 3 |  2 | 01/03/2016 | 
| 4 |  1 | 01/04/2016 | 
+----+----------+------------+ 

我需要把所有從業主表加上計數的信息購買人:

+-----------+-------------+-------------------+--------------+ 
| owners.id | owners.name | owners.birth_year | buylog.Count | 
+-----------+-------------+-------------------+--------------+ 
|   1 | John  |    1970 |   2 | 
|   2 | Jane  |    1980 |   2 | 
|   3 | Jack  |    1990 |   0 | 
|   4 | Josh  |    2000 |   0 | 
+-----------+-------------+-------------------+--------------+ 

我三編輯下面的查詢,但與返回錯誤:但是這

Select 
    o.id, 
    o.name, 
    o.birth_year, 
    Count(b.id) as Count 
From 
    owners o 
Left Outer Join 
    buylog b 
On 
    b.owner_id = o.id 
Group By o.id, 
    o.name, 
    o.birth_year 
+3

很好的解釋你的數據和查詢的工作。壞的工作,不張貼你的錯誤 –

回答

5

錯誤消息應該是很清楚的,你缺少一個group by條款可能有更好的表現:

SELECT o.id 
    , o.name 
    , o.birth_year 
    , COALESCE(b.Count, 0) AS Count 
FROM owners o 
LEFT JOIN (
    SELECT owner_id, COUNT(*) AS Count 
    FROM buylog 
    GROUP BY owner_id 
    ) AS b 
    ON b.owner_id = o.id; 

應該把完全相同的結果。

+0

所以我應該包括在GROUP BY子句除了計數的所有領域? – w8lessly

+0

是的,當您使用聚合函數時,所有不屬於聚合函數的屬性應該位於 – HoneyBadger

+0

組中。一般的GROUP BY規則指出:如果指定了GROUP BY子句,則SELECT列表中的每個列引用必須識別分組列或作爲設置功能的參數。 – jarlh

1

查詢通過HoneyBadger會做得很好,:

Select 
    o.id, 
    o.name, 
    o.birth_year, 
    Count(b.id) as Count 
From 
    owners o 
Left Outer Join 
    buylog b 
On 
    b.owner_id = o.id 
0
SELECT o.*, 
CASE 
    WHEN temp.Buylog_count IS NULL THEN 0 
    ELSE temp.Buylog_count 
END 
FROM Owners o 
LEFT JOIN 
(
    SELECT b.owner_id AS oid, COUNT(*) AS Buylog_count 
    FROM Buylog b 
    GROUP BY b.owner_id 
)temp ON temp.oid = o.id 
+0

如果'owner_id'的'buylog'表中沒有項目,'Buylog_count'將是NULL,而不是'0'。它不符合A/C。 –

+1

那麼,其餘的是或多或少的副本@ EvaldasBuinauskas的回答 – HoneyBadger

+0

而且就複製而言,它的可疑程度與您的答案類似於我的這裏:http://stackoverflow.com/questions/34762276/sql-use查詢作爲搜索條件的另一個查詢/ 34762926#comment57279741_34762926 – HoneyBadger