如何获取与 mysql 中的 concat 值字段相关的 COUNT 和 INNER JOIN
How to get COUNT and INNER JOIN related with concated value field in mysql
我有 2 table
table A
tag_id | Tag_name
1 | tg1
2 | tg2
3 | tg3
4 | tg4
table B
id | name |tag_id
1 | avq | 1,2,4
2 | bdq | 2
3 | abc | 3,2
4 | vdf | 1,4
5 | zxc | 3
我想 inner join 两个 tables 并使用 [=30 得到它的 count =] 格式如下
`tg1=> 2,tg2=> 3,tg3=> 2,tg4=> 2`
如何在单个 MySQL 查询中实现?
您需要创建关系 table。例如:
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 |
+------+--------+
在您的参考文献 table 中,您为一个 B 元素放置了很多标签。在此示例中,您看到通过引用分配的两个标签 b_id = 1
最好的选择是规范化第二个 table 并创建一个关联 table 来存储标签 ID 和第二个 table 的 ID。与此同时,以下内容应该可以完成工作,但长期 运行 你需要规范化 table 否则将来会发生更多问题
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 ;
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
我有 2 table
table A
tag_id | Tag_name
1 | tg1
2 | tg2
3 | tg3
4 | tg4
table B
id | name |tag_id
1 | avq | 1,2,4
2 | bdq | 2
3 | abc | 3,2
4 | vdf | 1,4
5 | zxc | 3
我想 inner join 两个 tables 并使用 [=30 得到它的 count =] 格式如下
`tg1=> 2,tg2=> 3,tg3=> 2,tg4=> 2`
如何在单个 MySQL 查询中实现?
您需要创建关系 table。例如:
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 |
+------+--------+
在您的参考文献 table 中,您为一个 B 元素放置了很多标签。在此示例中,您看到通过引用分配的两个标签 b_id = 1
最好的选择是规范化第二个 table 并创建一个关联 table 来存储标签 ID 和第二个 table 的 ID。与此同时,以下内容应该可以完成工作,但长期 运行 你需要规范化 table 否则将来会发生更多问题
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 ;
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