简体   繁体   English

Mysql查询选择行,或者匹配其他表上的行

[英]Mysql query to select rows and alternatively matching rows on other table

I've got two tables: 我有两张桌子:

user
ID --- Name ID ---姓名

posts
ID --- UserID --- Text --- Postdate ID --- UserID ---文本--- Postdate

Now I want to select all users and every post they've made in the past 15 minutes. 现在我想选择他们在过去15分钟内完成的所有用户和每个帖子。 I also want to display every user that didn't didn't even make a post with the matching conditions at all. 我还希望显示每个用户根本没有匹配条件的帖子。

I'm currently doing it this way: 我现在这样做:

$user_q = mysql_query("SELECT * FROM user");
while ($a = mysql_fetch_assoc($user_q))
{
     $post_q = mysql_query("SELECT * FROM posts WHERE Userid=".$a['ID']." AND Postdate >= DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
     //Do anything with this information
}

Do you have any ideas how I can put all this information in just one query? 您是否有任何想法如何将所有这些信息放在一个查询中? Doing so many queries makes the server running very slow. 执行这么多查询会使服务器运行速度很慢。

What you want is a left outer join: 你想要的是一个左外连接:

select u.*, p.*
from users u left outer join
     posts p
     on u.id = p.userid and
        p.Postdate >= DATE_SUB(NOW(), INTERVAL 15 MINUTE);

The left outer join keeps all the rows in the first table. left outer join保留第一个表中的所有行。 If nothing matches in the second table, using the condition, then the values are NULL for those fields. 如果第二个表中没有任何内容匹配,则使用条件,那些字段的值为NULL

EDIT: 编辑:

If you want to limit this to 50 random users, you can do this at the users level: 如果要将此限制为50个随机用户,可以在users级别执行此操作:

select u.*, p.*
from (select u.*
      from users u
      order by rand()
      limit 50
     ) u left outer join
     posts p
     on u.id = p.userid and
        p.Postdate >= DATE_SUB(NOW(), INTERVAL 15 MINUTE);

The order by rand() makes them random. order by rand()order by rand()使它们随机。 You could order by anything -- name, date created, whatever. 您可以通过任何方式订购 - 名称,创建日期,等等。 You can even leave the order by out and just take 50 arbitrary rows returned by the database. 您甚至可以退出order by ,只需获取数据库返回的50个任意行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM