Sql中表中匹配的两列值的计数对
我有两张桌子 品牌表 它是特定用户选择的品牌标识列表Sql中表中匹配的两列值的计数对,sql,database,Sql,Database,我有两张桌子 品牌表 它是特定用户选择的品牌标识列表 id_autoicrement | user_id | brand_id 1 | 5 | 7 2 | 5 | 3 3 | 5 | 1 4 | 9 | 3 5 | 9 | 7 6 |
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
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
产品表
它是特定用户选择的产品标识列表
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
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
编辑
对不起,我弄错了。
我想要品牌id和产品id的列表,它们由相同数量的用户使用,这些用户的品牌id和产品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
提前感谢。使用以下查询
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;
只需按用户、按品牌和产品分组将这两个表连接起来,就完成了
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提琴:。三个人回答了您最初的问题。虽然这个问题可能与你无关,但它似乎仍然有意义,可能对其他人有价值。请考虑将这个问题回溯到原来的版本,并为你的实际问题创建一个单独的问题。我第一次就弄错了请看我的编辑,很抱歉更改了问题@Thorsten KettnerI我看不出这与您原来的问题有什么不同。您需要所有选择的产品品牌组合,并知道有多少用户选择了这些组合。我的查询(仍然)是这样做的。你能解释一下我的解决方案和你期望的结果有什么不同吗?我不需要p.user\u id=b.user\u id语句。从对与您的p.user\u id=b.user\u id.不同的所有用户中进行计数。。我需要拥有相同品牌id和产品id的用户计数,但不检查他们的p.user_id=b.user_id我认为你错了。你有没有调查过SQL的问题?用户A选择品牌1和产品2和3。通过使用
p.user\u id=b.user\u id
从两个表中进行选择,我得到了用户的组合1-2和1-3。对于用户B,我将得到1-3和2-3,因此对于组合1-3,我将得到2的计数,正如您在请求中所描述的。