[英]group and count in mysql
I have table like this 我有这样的桌子
table1 表格1
col1
______
data1
data2
data3
data4
data5
and table2 和表2
data1
_________
data1,data2
data1
data3,data1
data5
data4,data5,data1
data2
Can I have query that joins both tables with result two column first column content table1.col1 list and column 2 content count of data that content like first column 我是否可以将两个表都与结果两列第一列的内容table1.col1列表和列2的内容进行连接的查询的内容
column1|column2
_______|_______
data1 | 4
data2 | 2
data3 | 1
data4 | 1
data5 | 2
For now I use query inside looping in PHP 目前,我在PHP循环中使用查询
$s="select col1 from table1";
foreach($conn->query($s) as $r);) {
echo "select count(*) from table2 where data1 like '%$r[col1]%' ";
}
If there is any query that can achieve without query inside looping. 如果有任何查询可以在循环内部进行而无需查询。
btw I use pdo query helper instead mysql_query, i just write a little code by using mysql_query. 顺便说一句,我使用pdo查询助手而不是mysql_query,我只是使用mysql_query编写了一些代码。
Thanks. 谢谢。
First of all is that you shouldn't keep multiple values in single field (table2) when you need it's values in SQL queries. 首先,当您在SQL查询中需要多个值时,不要在单个字段(表2)中保留多个值。
Anyway, you can utilize FIND_IN_SET()
MySQL's function to join both tables and then use GROUP BY
and COUNT(*)
to get what you need. 无论如何,您可以利用MySQL的FIND_IN_SET()
函数来连接两个表,然后使用GROUP BY
和COUNT(*)
来获得所需的信息。
SELECT table1.col1 as column1, count(*) as column2
FROM table1
LEFT JOIN tabl2 ON FIND_IN_SET(table1.col1,table2.data1)
GROUP BY table1.col1;
Although there's ready function to do such things, you should keep an eye on performance issues that may occur here. 尽管已经准备好执行此操作的功能,但您应注意此处可能发生的性能问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.