使用 WHERE IN 子句使用 MySQL 查询时出现问题
在我的网站上,我正在尝试编写一项功能,用户可以选择从其他用户那里获取“更新”。当用户单击“接收更新”时,它会将该用户 ID 以及他们想要接收更新的其他用户一起扔到数据库中。例如 (4,5,6,7,8)。我的表看起来像这样
members | updates
-----------------
id | id
updates | member_id
| content
| content_date
当我查询数据库时,我只想从更新表中提取来自members:updates 中已指定用户的更新。
$sql_updates = mysql_query("SELECT *
FROM updates a,
members b
WHERE a.member_id IN b.updates
ORDER BY a.content_date DESC
LIMIT 10");
while($row = mysql_fetch_array($sql_updates)) {
这是最好的方法吗?
On my website I am trying to program a feature where a user can choose to get 'updates' from another user. When a user clicks 'receive updates,' it throws that users ID in the database, alongside with other users they want to receive updates from. For Example (4,5,6,7,8). My tables look like this
members | updates
-----------------
id | id
updates | member_id
| content
| content_date
When I query the database I want to pull out of the updates table only the updates from the already specified users in members:updates.
$sql_updates = mysql_query("SELECT *
FROM updates a,
members b
WHERE a.member_id IN b.updates
ORDER BY a.content_date DESC
LIMIT 10");
while($row = mysql_fetch_array($sql_updates)) {
Is this the best way to go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,正确拼写列名称 -
mem_id
或member_id
,它应该是什么?其次,这只是一个简单的内部联接:First off, spell you column names correctly --
mem_id
ormember_id
, what shall it be? Second, this is just a plain inner join:在Mysql中,“IN”就像编程运算符的“OR”,如果您起诉IN,您需要提供一个b.updates数组,而不仅仅是列更新或使用子查询返回数组
其他或更好的方法可能是使用JOIN
in Mysql "IN" is like "OR" of programming operator if you are suing IN you need to provide an array of b.updates not just the column updates or use subquery to return array
Other or better way could be using JOIN
我建议使用第三个表“订阅”,它将链接“成员”和“更新”表。
示例表结构:
对于每个订阅(单击“接收更新”),您将在“订阅”表中创建一行。
I would recommend using a third table "subscriptions" which would link "members" and "updates" tables.
Sample table structure:
For each subscription (click on "receive updates"), you would create a row in "subscriptions" table.
在 in 有意义的情况下,join 可以为您提供额外的结果。通常我建议使用exists 运算符,因为它的执行方式与join 相同,但提供了in 的行为。稍后您可以使用distinct 来保存自己。
A join can give you extra results in cases where an in would make sense. Usually I recommend the exists operator because it performs the same as a join but gives the behavior of an in. You can save yourself using a distinct later on.