我在SQL中有一个包含N列的表。打电话给他们" Col1"," Col2",...," ColN"。我可以通过查询找出Col1中有多少独特元素:
select count(distinct Col1) from mytable
我可以为每列独立完成此操作。假设我在Col1中有M_1个唯一元素,在Col2中有M_2等,我可以用什么单个命令来查找我的数据集的所有可能组合的总数?也就是说,单个查询会为我计算什么(M_1 * M_2 * ... * M_N)?
PS:这里对SQL很新,所以我不确定这是否重要 - 但我在Windows上使用MySQL Workbench。
答案 0 :(得分:1)
SELECT COUNT(*)
FROM (SELECT DISTINCT col1 FROM YourTable) AS t1
CROSS JOIN (SELECT DISTINCT col2 FROM YourTable) AS t2
CROSS JOIN (SELECT DISTINCT col3 FROM YourTable) AS t3
...
CROSS JOIN
计算给定表格之间的叉积。
另一种写作方式是:
SELECT COUNT(DISTINCT t1.col1, t2.col2, t3.col3, ...)
FROM YourTable AS t1
CROSS JOIN YourTable AS t2
CROSS JOIN YourTable AS t3
...
但最简单的可能是:
SELECT COUNT(DISTINCT col1)*COUNT(DISTINCT col2)*COUNT(DISTINCT col3)*...
FROM YourTable
这不需要计算任何交叉产品,因此它应该是最有效的。如果列上有索引,它甚至不必读取表数据,它可以使用索引完成。