使用WHERE子句在一个SQL查询中检查数组中的值 [英] Checking value in an array inside one SQL query with WHERE clause

查看:927
本文介绍了使用WHERE子句在一个SQL查询中检查数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这在sql(使用php作为服务器端)中实际上是可行的,其中您有一个值数组(数字),然后您尝试根据该数组中的值检索数据..

我有一个sql表:

posts(
    id int(11) primary key,
    posts varchar(140),
    user_id int(11) foreign key
);

我现在编写一个查询来检索帖子":

$query="SELECT * FROM posts WHERE user_id=(**Array of select user_id's**)";

是否有任何sql内置函数来检查数组中的值?还是应该为此使用PHP?

我实际上是在尝试实现Twitter模式,以显示我们关注的人的帖子.

解决方案

SQL无法解析PHP数组.试试这个:

$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})";

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..

I have a sql table:

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?

I am actually trying to implement the twitter model of showing posts of people whom we follow.

解决方案

SQL can't parse PHP arrays. Try this:

$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})";

这篇关于使用WHERE子句在一个SQL查询中检查数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆