简体   繁体   English

如何在mysql中获取与concated value字段相关的COUNT和INNER JOIN

[英]How to get COUNT and INNER JOIN related with concated value field in mysql

I have 2 tables我有2张桌子

table A

tag_id | Tag_name

1      | tg1
2      | tg2
3      | tg3
4      | tg4

table B表B

id | name |tag_id

1  | avq    | 1,2,4
2  | bdq    | 2
3  | abc    | 3,2
4  | vdf    | 1,4
5  | zxc    | 3

I want to inner join both tables and get its count using tag_id in the following format我想内部连接两个表并使用以下格式的tag_id获取其计数

`tg1=> 2,tg2=> 3,tg3=> 2,tg4=> 2`

How is it possible in a single MySQL query ?在单个MySQL 查询中怎么可能?

The best option is to normalize the 2nd table and create an association table for storing the tag id and the id of the 2nd table.最好的选择是对第二个表进行规范化并创建一个关联表来存储标签 id 和第二个表的 id。 In the meanwhile the following should do the job but for long run you need to normalize the table else more problems will happen in future同时,以下内容应该可以完成这项工作,但从长远来看,您需要对表格进行标准化,否则将来会发生更多问题

select 
t1.Tag_name, count(*) as total 
from tableA t1 
join tableB t2 on find_in_set(t1.tag_id,t2.tag_id) > 0 
group by t1.tag_id ;

You need to create relation table.您需要创建关系表。 For example:例如:

Tag table:
+----+----------+
| id | name     |
+----+----------+
| 1  | Tag name |
+----+----------+
| 2  | Tag 2    |
+----+----------+

B Table:
+----+-----------+
| id | title     |
+----+-----------+
| 1  | Any title |
+----+-----------+

Reference table ex. :

+------+--------+
| b_id | tag_id |
+------+--------+
| 1    | 1      |
+------+--------+
| 1    | 2      |
+------+--------+

In your reference table you put many tags for one B element.在您的参考表中,您为一个 B 元素放置了许多标签。 In this example you see two tags assigned by reference to b_id = 1在此示例中,您会看到通过引用 b_id = 1 分配的两个标签

select tag_name, count(position)
from (
select a.tag_name, FIND_IN_SET(a.tag_id,b.tag_id) as position
from a,b
) as tmpTB
where position !=0
group by tag_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM