'repetition-operator operand invalid' 来自带有 CONCAT 的 REGEXP

'repetition-operator operand invalid' from REGEXP with CONCAT

我的SQLtable结构是这样的

id available_sizes
1 S,M,L
2 L,XL
3 Small,Large
4 30,32,33

这里我想过滤所有由M或L尺寸组成的ID。我用 CONCAT 和 REGEXP 试过这个操作,我用 PHP

试过这个语句
$stmt = $conn->prepare('SELECT * FROM table WHERE CONCAT(",", available_sizes, ",") REGEXP ",(?|?),"');

$param1 = "M";
$param2 = "L";

$stmt->bind_param("ss", $param1, $param2);
$stmt->execute();
$result = $stmt->get_result();

Bt 它显示错误:'repetition-operator operand invalid' 来自正则表达式查询。

你的问题是因为它在 REGEXP 部分没有说明 table。

SELECT * FROM table WHERE yourcolumn REGEXP your expression;

您可以用 REGEXP 匹配 \b(M|L)\b。在 PHP 中构建整个交替,然后将其绑定到 MySQL 查询中的占位符:

$stmt = $conn->prepare("SELECT * FROM table WHERE available_sizes REGEXP ?");
$params = array("M", "L");
$regex = "[[:<:]](" . implode("|", $params) . ")[[:>:]]";

$stmt->bind_param("s", $regex);
$stmt->execute();
$result = $stmt->get_result();

注意:在 MySQL 8+ 上,使用上面的内容并进行以下小改动:

$regex = "\b(" . implode("|", $params) . ")\b";