php 使用 WHERE 子句检查一个 SQL 查询中数组中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8270134/
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
Checking value in an array inside one SQL query with WHERE clause
提问by Robbie Dc
I want to know is this practically possible in sql(using php as server-side), where in you have an array of values(numbers), and you try to retrieve data based on values inside that array..
我想知道这在 sql(使用 php 作为服务器端)中实际上是否可行,其中您有一个值(数字)数组,并且您尝试根据该数组中的值检索数据。
I have a sql table:
我有一个 sql 表:
posts(
id int(11) primary key,
posts varchar(140),
user_id int(11) foreign key
);
I write a query now to retrieve 'posts':
我现在写一个查询来检索“帖子”:
$query="SELECT * FROM posts WHERE user_id=(**Array of select user_id's**)";
Is there any sql in-built function to check values inside an array? or should I be using PHP for this?
是否有任何 sql 内置函数来检查数组中的值?或者我应该为此使用PHP?
I am actually trying to implement the twitter model of showing posts of people whom we follow.
我实际上是在尝试实现显示我们关注的人的帖子的 twitter 模型。
回答by liquorvicar
Yes, this is easily possible. You need to look at MySQL's IN function
是的,这很容易实现。你需要看看MySQL的IN函数
Your query would be something like
您的查询将类似于
SELECT * FROM posts WHERE user_id IN (1,2,3,4,5,6)
You can build the bit in between the parentheses in PHP using implode()
您可以使用implode()在 PHP 中的括号之间构建位
回答by Hikaru-Shindo
SQL can't parse PHP arrays. Try this:
SQL 无法解析 PHP 数组。尝试这个:
$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})";
回答by Bas Slagter
Take a look at this page : WHERE ... IN. You can use the IN operator to check if a certain value exists within an list of values.
看看这个页面:WHERE ... IN。您可以使用 IN 运算符来检查某个值是否存在于值列表中。
回答by Emy
Yea you will have to you use following syntax
是的,您必须使用以下语法
SELECT 'value'
IN (array)