简体   繁体   English

如何 select 行,其中特定字符串列与 json 数组中的至少一个值匹配?

[英]how to select rows where a specific string column matches at least one value inside a json array?

SELECT name FROM  accounts WHERE Name in ("name1","name2");

the values are being sent inside a json array这些值在 json 数组中发送

["name1","name2"] [“名称1”,“名称2”]

currently i just convert the array into json string and remove the first and last characters目前我只是将数组转换为 json 字符串并删除第一个和最后一个字符

"name1","name2" “名称 1”、“名称 2”

but could i just keep the array intact?但我可以保持阵列完好无损吗? i tried json_contains我试过 json_contains

SELECT name FROM  accounts WHERE JSON_CONTAINS(name,'["name1","name2"]');

my understanding as to which why that didn't work is because name column isn't json string array我的理解为什么这不起作用是因为名称列不是 json 字符串数组

Core issue is you can't "prepare" flex statements without some sort of preprocessing.核心问题是你不能在没有某种预处理的情况下“准备”弹性语句。

Generally you'll want to do input validation etc, on the application side regardless, and then use some sort of pre-constructor if you're not using an ORM.通常,您无论如何都希望在应用程序端进行输入验证等,然后如果您不使用 ORM,则使用某种预构造函数。

ie: IE:

$values = ["name1", "name2"];

// Validation should happen here

$inputs = substr(str_repeat("?,", count($values)), 0, -1);
$bind   = str_repeat("s", count($values));
$sqli   = "SELECT name FROM  accounts WHERE Name in ($inputs);";
...
$stmt->bind_param($bind, ...$values);
...

You can use the same principal for PDO as well, but regaredless you're gunna want to handle the validation layer on the application side, and there is no "easy" way to inject "IN" statements into prepared SQL.您也可以对 PDO 使用相同的主体,但无论如何您都想在应用程序端处理验证层,并且没有“简单”的方法将“IN”语句注入准备好的 SQL。

暂无
暂无

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

相关问题 MySQL-如何选择主键多次出现并且至少另一个字段匹配的行? - MySQL - how to select rows where a primary key occurs more than once AND at least one of another field matches? SQL select 具有相同代码的所有行,其中至少一行包含特定值 - SQL select all rows with the same ticker where at least one of the rows includes a specific value MySQL - 选择 json_column 具有特定值的行 - MySQL - Select rows where json_column has specific value SQL选择在另一列中具有至少一个特定值的所有非唯一行 - SQL select all non-unique rows that have at least one specific value in another column 具有原生JSON支持的MySQL 5.7-如何选择数组中存在特定值的行? - MySQL 5.7 with native JSON support - how to select rows where a specific value exists in array? MySQL选择5行,其中一个合并列的总和最匹配确定的值 - Mysql Select 5 rows where sum of one combined column best matches a determined value SQL选择行,其中每个ID至少有一个值 - SQL select rows where at least one value is something per id Select 行在 JSON 列中具有特定值 - Select rows with specific value in JSON column SQL:如何 select 行的列值至少出现 1 次? - SQL: How to select rows with a column value that appears at least 1 times? SQL查询以选择行计数,即使变量列表中的列中至少有一个值匹配也是如此 - Sql query to select row count even when at least one value matches in column out of list of variables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM