MySQL跨列比较以限制值的实例数
我有一个表,其中有十个字段,所有字段的值都可以在一个定义的集合内。我只想从该表中选择十列重复相同值不超过x次的记录 例如:MySQL跨列比较以限制值的实例数,mysql,sql,select,comparison,Mysql,Sql,Select,Comparison,我有一个表,其中有十个字段,所有字段的值都可以在一个定义的集合内。我只想从该表中选择十列重复相同值不超过x次的记录 例如: id col1 col2 col3 col4 col5 col6 col7 col8 col9 -------------------------------------------------------- 1 a b c d e f g h i 2 a a a
id col1 col2 col3 col4 col5 col6 col7 col8 col9
--------------------------------------------------------
1 a b c d e f g h i
2 a a a b c d e f g
3 a a a a b c d e f
4 b c d e f g h i j
5 c c c c d c c f g
给定上面的示例表,我希望我的SELECT返回记录1、2和4。第3行和第5行各有四列或更多列具有相同的值
到目前为止,我提出的唯一想法是连接所有十列,然后进行迭代instr调用,但这将是非常静态的,不利于性能
感谢您的关注。您可以使用union all将所有值合并到一列中,并对每个id进行聚合
在取消激活数据后,可以通过两个聚合级别执行此操作:
select id
from (select id, col, count(*) as cnt
from ((select id, col1 as col from t) union all
(select id, col2 as col from t) union all
. . .
) t
group by id, col
) t
where cnt < 4
group by id;
你只喝可乐吗。。可乐9号?这是固定的吗?如果您有一个表,其中一个值在多个列中表示相同的内容,那么您的设计中就有一个反模式。这些值应存储在单独表中的各行上,并链接回第一个表的主键。。。然后加入。。。分组方式。。。有伯爵。。。
select id
from (select id, col, count(*) as cnt
from ((select id, col1 as col from t) union all
(select id, col2 as col from t) union all
. . .
) t
group by id, col
) t
where cnt < 4
group by id;
select t.*
from t
where length(replace(concat(col1, . . ., col9), col1, '') < 6 or
length(replace(concat(col1, . . ., col9), col2, '') < 6 or
. . .;
select t.*
from t
where replace(concat(concat_ws(',', col1, . . ., col9), ','),
concat(col1, ',')) not like '%,%,%,%,%,%,%' or
. . .