如何从辅助表中获取唯一的行数

时间:2011-02-23 12:00:20

标签: mysql database

create table pro_category (id primary key, product_id int, category_id int)
insert into pro_category (1, 1, 1)
insert into pro_category (1, 1, 2)
insert into pro_category (1, 2, 1)
insert into pro_category (1, 2, 1)

如何从辅助表中获取唯一的行数(例如,在上述情况下,涉及2个产品ID,因此我希望得到2的答案。)

2 个答案:

答案 0 :(得分:1)

使用count(distinct)

select count(distinct product_id) from pro_category

答案 1 :(得分:1)

SELECT COUNT(DISTINCT product_id) FROM pro_category

这将返回2