[英]How to get COUNT and INNER JOIN related with concated value field in mysql
我有2張桌子
table A
tag_id | Tag_name
1 | tg1
2 | tg2
3 | tg3
4 | tg4
表B
id | name |tag_id
1 | avq | 1,2,4
2 | bdq | 2
3 | abc | 3,2
4 | vdf | 1,4
5 | zxc | 3
我想內部連接兩個表並使用以下格式的tag_id獲取其計數
`tg1=> 2,tg2=> 3,tg3=> 2,tg4=> 2`
在單個MySQL 查詢中怎么可能?
最好的選擇是對第二個表進行規范化並創建一個關聯表來存儲標簽 id 和第二個表的 id。 同時,以下內容應該可以完成這項工作,但從長遠來看,您需要對表格進行標准化,否則將來會發生更多問題
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 ;
您需要創建關系表。 例如:
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 |
+------+--------+
在您的參考表中,您為一個 B 元素放置了許多標簽。 在此示例中,您會看到通過引用 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.