简体   繁体   English

从 Mysql 获取逗号分隔的字符串

[英]Get comma separated string from Mysql

I'm saving a string from PHP to MySQL like this..我正在从 PHP 到 MySQL 像这样保存一个字符串..

$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");

I'm then trying to extract data from the table if $a = "15"然后我尝试从表中提取数据 if $a = "15"

$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");

How can I easily match what's in $groupid to $a, while extracting it?如何在提取时轻松地将 $groupid 中的内容与 $a 匹配? Can I do that with MySQL?我可以用 MySQL 做到这一点吗?

You can use the find_in_set function here.您可以在此处使用find_in_set function。

SELECT * 
    FROM table 
    WHERE ustaffid='$ustaffid' 
        AND FIND_IN_SET('$a', groupid) > 0

If $a contains only one id I would suggest seperating it into multiple records, because in string search (/ select) is slower.如果$a仅包含一个 id,我建议将其分成多条记录,因为在字符串搜索 (/select) 中速度较慢。

I don't know if having spaces in the groupid columns would affect the find_in_set MySQL function, and as @PeeHaa notes searching inside a string is slower and is hard to optimize with indexes.我不知道groupid列中的空格是否会影响find_in_set MySQL function,并且正如@PeeHaa 指出的那样,在字符串中搜索速度较慢,并且很难使用索引进行优化。

You should really consider modifying the database schema and normalize it so that instead of saving multiple values in a column, use a dependent table and relate multiple rows to the main table for each groupid value.您确实应该考虑修改数据库架构并将其规范化,以便使用依赖表并将每个groupid值的多行与主表相关联,而不是在列中保存多个值。 That's what relational databases are for.这就是关系数据库的用途。

Expanding on @ecchymose's answer, you can use a regex instead of LIKE.扩展@ecchymose 的答案,您可以使用正则表达式而不是 LIKE。

SELECT *
FROM table
WHERE ustaffid='$ustaffid'
AND groupid RLIKE '(^|, )$a(, |$)'

Note: You may need to escape the last $ with a \ .注意:您可能需要使用\转义最后一个$

Note 2: This isn't the optimal solution.注意 2:这不是最佳解决方案。 You should really have a separate row for each ID (with the ID being the PRIMARY key).每个 ID 都应该有一个单独的行(ID 是 PRIMARY 键)。

SELECT * 
FROM table 
WHERE ustaffid='$ustaffid' 
AND groupid LIKE '%$a,%'

But you have to end your string with a comma at the end.但是你必须在最后用逗号结束你的字符串。

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

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