我有一个mysql字段,它可能包含单个center_id值,如AB或csv值,如AB、AJ等。
目前,我在php中做了以下操作:
$usercenter = $_SESSION['usercenter'];
$searchForValue = ',';
if( strpos($usercenter, $searchForValue) !== false ) {
$centerid = explode(',', $usercenter);
}
else {
$centerid = $usercenter;
}在sql查询中,我需要:
SELECT id,node
FROM followup
WHERE center_id IN('".implode("','",$centerid)."')如果有csv值,则工作正常。如何编写查询来检查csv值和单个值?
请求帮助.。
发布于 2020-07-08 12:19:42
考虑到您的模式,我能想到的唯一解决方案就是使用LIKE。
SELECT id, node FROM followup WHERE center_id LIKE "%AD%";
但是,这也将选择带有CAD、ADA等的行,并且只能在每个条件下检查单个选项(因此您必须对多个LIKE语句使用AND/OR )。
而且你的解决方案是一种反模式。通常你会用一对多的关系来处理这个问题。
发布于 2020-07-08 12:33:40
虽然它不使用索引值(因此对于庞大的数据集,它可能相当慢),但是您可以使用MySQL函数FIND_IN_SET()。这可以在逗号分隔的列表中搜索单个值。
虽然这不能同时搜索多个值,但根据我在问题中的理解,您只是一次寻找一个值。
该函数接受要搜索的值(区分大小写!),然后是要搜索的列。
SELECT id,node
FROM followup
WHERE FIND_IN_SET('AB', center_id)如果是相反的情况,并且您希望在WHERE IN (..)中使用所有这些值,那么无论它是一个还是非explode(),您都可以只使用它--返回值将是一个数组,您可以使用它,不管它的长度是1还是更长。但是,在这样做时,应该使用预先准备好的语句。您可以通过根据数组的长度生成动态查询来实现这一点。
MySQLi:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions - this allows you to automagically check for errors
// Create connection, $mysqli = new mysqli(...);
$parts = explode(',', $usercenter); // Split the comma-separated values
if (empty($parts)) {
// Handle it
}
// Generate dynamic SQL, execute and fetch
$stmt = $mysqli->prepare("SELECT id, node
FROM followup
WHERE center_id IN (".implode(',', array_fill(0, count($parts ), '?')).")");
$stmt->bind_param(str_repeat("s", count($parts)), ...$parts);
$stmt->execute();
$stmt->bind_result($id, $node);
while ($stmt->fetch()) {
// Use $id and $node for each row
}
$stmt->close();PDO:
// Create connection, $pdo = new PDO(...);
// You should set PDO to throw exceptions on errors
$parts = explode(',', $usercenter); // Split the comma-separated values
if (empty($parts)) {
// Handle it
}
$stmt = $pdo->prepare("SELECT id, node
FROM followup
WHERE center_id IN (".implode(',', array_fill(0, count($parts ), '?')).")");
$stmt->execute([...$parts]);
while ($row = $stmt->fetch()) {
// Use $row['id'] and $row['node'] for each row
}您还可能希望在爆炸后筛选空值。
发布于 2020-07-08 13:02:23
应该使用FIND_IN_SET()函数返回字符串在字符串列表中的位置。它同时使用逗号分隔的值和单独的值。尝试以下查询
SELECT id,node
FROM followup
WHERE FIND_IN_SET('center_id','".implode("','",$centerid)."')https://stackoverflow.com/questions/62794567
复制相似问题