2016-06-10 68 views
1

我有一個表結構像以下:獲得來自許多相應的和非對應的值,以許多表

品牌=>瀏覽歷史< =用戶

史是多對多的表,幷包含下列值:

brandId, userId and points 

我需要獲得所有具有USER SCORED分數的點以及所有品牌的用戶沒有相應的值的所有品牌。這將是這個樣子:

brandId => 1 (has corresponding value) => 5 points 
brandId => 2 (no corresponding value) => null (column points is null) 

等等...

誰能幫我這個?

編輯:

嗨戈登,我修改您的查詢,看起來像這樣:

select b.*, sum(h.points) as points 
from brands b left join 
    histories h 
    on b.id = h.brandId 
    and h.userId = 2866 and h.brandId = 2 
group by h.brandId 

我需要有第二個條件h.brandID = 2 //或其他一些值,使它一次只返回1條記錄,如果沒有記錄,我想列的值爲空,如果不是,它應該總和所有點數n在列中顯示它們...

回答

0

I認爲你只想要一個left joingroup by

select b.brandId, sum(h.points) 
from brands b left join 
    histories h 
    on b.brandid = h.brandid and h.userId = $userId 
group by b.brandId; 

如果用戶的histories中沒有行,則值爲NULL

編輯:

如果使用left join,那麼group by應該是從第一個表中的列:

select b.*, sum(h.points) as points 
from brands b left join 
    histories h 
    on b.id = h.brandId and 
     h.userId = 2866 and h.brandId = 2 
group by b.brandId;