如何在MySQL中查询country字段匹配指定字符串中子串的行?
从MySQL中查询符合指定国家列表的行
需求:从proxylist表中获取所有country字段值属于偏好国家列表的行,偏好国家列表存储在变量$pref_country中。
原代码问题
你的原SQL逻辑错误,LIKE '%$pref_country%'是判断country字段是否包含整个偏好列表字符串,这和实际需求完全相反。同时直接将变量拼接进SQL语句存在SQL注入风险,生产环境中严禁这么做。
原代码:
$pref_country = 'AU-Australia,CA-Canada,ES-Spain,GB-United Kingdom'; $rowRes = mysqli_query($mydb, "SELECT * FROM `proxylist` WHERE `country` LIKE `%$pref_country%`"); while($row = mysqli_fetch_array($rowRes)) { echo $row ['country'] . '<br/>'; }
修正方案
方案1:使用FIND_IN_SET函数
利用MySQL的FIND_IN_SET函数,直接判断country值是否在逗号分隔的偏好列表中,搭配预处理语句避免注入:
$pref_country = 'AU-Australia,CA-Canada,ES-Spain,GB-United Kingdom'; // 构建预处理查询 $query = "SELECT * FROM `proxylist` WHERE FIND_IN_SET(`country`, ?)"; $stmt = mysqli_prepare($mydb, $query); // 绑定参数 mysqli_stmt_bind_param($stmt, 's', $pref_country); mysqli_stmt_execute($stmt); $rowRes = mysqli_stmt_get_result($stmt); while($row = mysqli_fetch_array($rowRes)) { echo $row['country'] . '<br/>'; }
方案2:拆分列表用IN条件
将偏好列表拆分为数组,生成IN语句的占位符,再通过预处理绑定参数,适合数据量较大的场景:
$pref_country = 'AU-Australia,CA-Canada,ES-Spain,GB-United Kingdom'; // 拆分字符串为国家数组 $countries = explode(',', $pref_country); // 生成对应数量的占位符 $placeholders = implode(',', array_fill(0, count($countries), '?')); // 构建IN条件的预处理SQL $query = "SELECT * FROM `proxylist` WHERE `country` IN ($placeholders)"; $stmt = mysqli_prepare($mydb, $query); // 绑定所有国家参数 mysqli_stmt_bind_param($stmt, str_repeat('s', count($countries)), ...$countries); mysqli_stmt_execute($stmt); $rowRes = mysqli_stmt_get_result($stmt); while($row = mysqli_fetch_array($rowRes)) { echo $row['country'] . '<br/>'; }
原表数据
| SL_INDEX | IP_PORT | COUNTRY_NAME |
|---|---|---|
| 100002 | IP:PORT | AU-Australia |
| 100003 | IP:PORT | CA-Canada |
| 100004 | IP:PORT | FR-France |
| 100005 | IP:PORT | AU-Australia |
| 100006 | IP:PORT | ES-Spain |
| 100007 | IP:PORT | GB-United Kingdom |
| 100008 | IP:PORT | ES-Spain |
| 100009 | IP:PORT | US-United States |
执行结果
两种方案都会返回FR-France和US-United States之外的所有行,即符合偏好列表的国家记录。
内容的提问来源于stack exchange,提问作者Nimesh
相关产品推荐
相关产品推荐

