我有一个数据库,其中包含一个包含所有代码的表,另一个表包含适用于无法转换为主键的数据的代码(因此存在很大问题)。有时代码在评论部分中以“E1 / D2 / E3”的方式保存,因此多个代码可以出现在一个评论中
我需要的是获取某个级别的代码列表,然后将其与LIKE语句一起使用,以查找每个代码在此特定数据库中存在的次数。例如。
计算评论表的代码列中每个代码的存在次数。我想要得到这个级别的代码列表然后我坚持下去。请帮忙
代码表:
+----+-----------+-----+
|Code|Description|Level|
+----+-----------+-----+
|A1 |desc |1 |
+----+-----------+-----+
|A2 |desc |1 |
+----+-----------+-----+
|A3 |desc |1 |
+----+-----------+-----+
|A4 |desc |1 |
+----+-----------+-----+
|A1.1|desc |2 |
+----+-----------+-----+
|A2.1|desc |2 |
+----+-----------+-----+
|A3.1|desc |2 |
+----+-----------+-----+
|A4.1|desc |2 |
+----+-----------+-----+
评论表:
+-------------+----------+-------------+
|Comment |Codes |Location |
+-------------+----------+-------------+
|Hello there |A1/A1.1/A2|Somewhere |
+-------------+----------+-------------+
|How are you |A4/A7/B1.1|Long time ago|
+-------------+----------+-------------+
|My name is...|B1/B2/B3 |Somewhere |
+-------------+----------+-------------+
现在我需要的是计算每个元组的评论部分中每个级别1的代码发生的次数。
答案 0 :(得分:1)
如果您的意思是每个代码出现在评论表的代码列中的频率:
select co.code, count(*)
from comments c join
codes co
on find_in_set(co.code, replace(c.codes, '/', ',')) > 0 and
co.level = 1
group by co.code;
编辑:
您也可以使用like
:
select co.code, count(*)
from comments c join
codes co
on concat('/', c.codes, '/') like concat('%/', co.code, '/%')
co.level = 1
group by co.code;
请注意,在开头和结尾附加分隔符以确保完全匹配。