2014-10-27 61 views
0

我有兩個表計數對在SQL兩個列值的它們是匹配表中

牌子表

它是由特定的用戶選擇的brand_id的列表。

id_autoicrement | user_id | brand_id 

       1 | 5  | 7 
       2 | 5  | 3 
       3 | 5  | 1 
       4 | 9  | 3 
       5 | 9  | 7 
       6 | 2  | 3 
       7 | 2  | 7 
       8 | 4  | 3 

產品列表

它是由特定的用戶所選擇的product_id的列表。

id_autoicrement | user_id | product_id 

       1 | 5  | 4 
       2 | 5  | 1 
       3 | 5  | 2 
       4 | 9  | 1 
       5 | 9  | 4 
       6 | 2  | 1 
       7 | 2  | 4 
       8 | 4  | 1 

編輯

對不起,我弄錯了。 我想要brand_id和product_id的列表,它們由brand_id和product_id值相同的用戶數相同。上面的表是一樣的。

User A        User B 

brand_id | product_id    brand_id | product_id 

     1 | 2        1 | 3 
      | 3        2 

相同數量由不同的用戶對...

User A has two pairs        User B has two paris 

brand_id 1 and product_id 2      brand_id 1 and product_id 3 
brand_id 1 and product_id 3      brand_id 2 and product_id 3 

結果應該是像

brand_id product_id -> combination 
    1   2  -> 1 
    1   3  -> 2 
    2   3  -> 1 

在此先感謝。

+0

三個人回答了您的原始問題。雖然這個問題可能與你無關,但它似乎仍然有意義,可能對其他人有價值。請考慮將此問題回滾到原始版本,併爲您的實際問題創建一個單獨的問題。 – 2014-10-27 14:23:54

+0

@AndriyM我再次道歉。我第一次弄錯了 – Nepster 2014-10-28 07:43:08

回答

1

用戶只需連接兩個表只,按品牌和產品,你就大功告成了。

select product_id, brand_id, count(*) 
from brands b 
inner join product p on p.user_id = b.user_id 
group by product_id, brand_id; 

該連接爲每個用戶 - 產品品牌組合創建一條記錄。然後按產品和品牌進行分組,您可以計算選擇產品品牌組合的用戶。

這是一個SQL小提琴:http://sqlfiddle.com/#!6/f868a/2

+0

看到我的編輯,並且很抱歉改變了問題@Thorsten Kettner – Nepster 2014-10-28 07:53:29

+0

我不明白這和你原來的問題有什麼不同。您需要所有選擇的產品品牌組合,並知道有多少用戶選擇了該組合。這是(仍然)我的查詢所做的。你能解釋一下我的解決方案和你的預期結果有什麼不同嗎? – 2014-10-28 07:59:02

+0

我不需要p.user_id = b.user_id語句。從所有用戶的對數相同,而不是你的p.user_id = b.user_id ..我需要計數的用戶具有相同的brand_id和product_id對,而不檢查他們的p.user_id = b.user_id – Nepster 2014-10-28 08:25:55

0

使用下面的查詢

select product_id,brand_id , product_users as count from 
(
select count(user_id) product_users, product_id from product_table 
) a, 
(
select count(user_id) brand_users, brand_id from brand_table 
) b 
where a.product_users = b.brand_users;