【问题标题】:How to get COUNT and INNER JOIN related with concated value field in mysql如何在mysql中获取与连接值字段相关的COUNT和INNER JOIN
【发布时间】:2016-01-03 01:48:54
【问题描述】:

我有两张桌子

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

我想 inner join 两个表并使用 tag_id 以下列格式获取其 count

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

如何在单个 MySQL 查询中实现?

【问题讨论】:

  • 您确实需要将表 B 规范化为每行只有一个标签的东西。在目前的状态下,很难用它做任何事情。

标签: php mysql count inner-join concat


【解决方案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

【讨论】:

  • 你能补充一点解释吗?
【解决方案2】:

最好的选择是对第二张表进行规范化,并创建一个关联表来存储标签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 ;

【讨论】:

  • 谢谢 Abhik Chakraborty
【解决方案3】:

您需要创建关系表。例如:

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 分配的两个标签

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2016-11-24
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多