php MySQL - 如何选择值在数组中的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4037145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - How to select rows where value is in array?
提问by Tomas
Ok, normally I know you would do something like this if you knew the array values (1,2,3 in this case):
好的,通常我知道如果您知道数组值(在这种情况下为 1,2,3),您会做这样的事情:
SELECT * WHERE id IN (1,2,3)
But I don't know the array value, I just know the value I want to find is 'stored' in the array:
但我不知道数组值,我只知道我要查找的值“存储”在数组中:
SELECT * WHERE 3 IN (ids) // Where 'ids' is an array of values 1,2,3
Which doesn't work. Is there another way to do this?
哪个不起作用。有没有另一种方法可以做到这一点?
回答by OMG Ponies
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
回答by VoteyDisciple
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
当查询到达 SQL 时,您必须已经扩展了列表。这样做的简单方法是,如果您使用来自某个内部可信数据源的 ID,您可以 100% 确定它们是整数(例如,如果您之前从数据库中选择它们)是这样的:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
但是,如果您的数据来自用户,则需要确保仅获取整数值,也许最容易像这样:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
回答by Aunik Rahman
If the array element is not integer you can use something like below :
如果数组元素不是整数,您可以使用以下内容:
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
回答by doug
If you use the FIND_IN_SET
function:
如果您使用该FIND_IN_SET
功能:
FIND_IN_SET(a, columnname)
yields all the records that have "a" in them, alone or with others
FIND_IN_SET(a, columnname)
单独或与其他人一起产生所有包含“a”的记录
AND
和
FIND_IN_SET(columnname, a)
yields only the records that have "a" in them alone, NOT the ones with the others
FIND_IN_SET(columnname, a)
仅生成仅包含“a”的记录,而不生成其他记录
So if record1 is (a,b,c) and record2 is (a)
所以如果 record1 是 (a,b,c) 而 record2 是 (a)
FIND_IN_SET(columnname, a)
yields only record2 whereas FIND_IN_SET(a, columnname)
yields both records.
FIND_IN_SET(columnname, a)
只产生 record2 而FIND_IN_SET(a, columnname)
产生两个记录。