MySQL select where 等于多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6877698/
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 select where equal to multiple values
提问by frank
I have two databases, where I store who is following who and another which stores the posts the user makes.
我有两个数据库,我存储谁在关注谁,另一个存储用户发表的帖子。
I want to select all of the people a user is following from the following database and echo out the usernames of those who that user is following and query the posts database for posts of that user.
我想从以下数据库中选择用户关注的所有人员,并回显该用户关注的用户的用户名,并在帖子数据库中查询该用户的帖子。
My problem is what if a user is following multiple users, I echoed out of the user id's of the people this user is following and I get 44443344330
我的问题是,如果一个用户关注多个用户,我会从该用户关注的人的用户 ID 中回显出来,然后我得到 44443344330
When I separate each id with commans, I get:
当我用命令分隔每个 id 时,我得到:
44,44,33,44,33,0,
so let's give that a variable of $user_ids
;
所以让我们给它一个变量$user_ids
;
$user_ids = "44,44,33,44,33,0, ";
the query:
查询:
$get_posts = mysql_query("SELECT * FROM posts WHERE userid = '$user_ids'");
but all it does is show the records of the first user id, 44.
但它所做的只是显示第一个用户 ID 44 的记录。
How can I retrieve all of the records for all the users?
如何检索所有用户的所有记录?
回答by Kerrek SB
The query should be:
查询应该是:
SELECT * FROM posts WHERE userid IN (44,44,33,44,33,0)
However, you may have to rethink your data model and make sure it is normalized, so that you can express this construction directly in the databse without echoing into a comma-separated string.
但是,您可能必须重新考虑您的数据模型并确保它是规范化的,以便您可以直接在数据库中表达这种结构,而无需回显到逗号分隔的字符串中。
Why do you have two databases? Do you mean two tables?
为什么你有两个数据库?你是说两张桌子吗?
回答by james_bond
Maybe you want to use IN
也许你想用 IN
SELECT * FROM posts WHERE userid IN ($user_ids)
回答by ain
Assuming you have two tabels, not databases, and that the table (lets call it "friends") which describes who is following who is like
假设您有两个表格,而不是数据库,并且描述谁在关注谁的表格(我们称之为“朋友”)
table friends(
userid
friendid
)
then query to get posts posted by X's friends would be
然后查询以获取 X 的朋友发布的帖子将是
SELECT
p.*
FROM posts p
JOIN friends f ON(p.userid = f.friendid)
WHERE f.userid = X
回答by Ethilé Landry Tanon Abédjinan
$var= str_replace(","," or userid = ","userid =$your_data_from_db");
your myqsl_query = SELECT * FROM posts where $var
您的 myqsl_query = SELECT * FROM posts where $var
回答by Shaun Hare
$get_posts = mysql_query("SELECT * FROM posts WHERE userid in '($user_ids)'");