Mysql query to select rows and alternatively matching rows on other table -
i've got 2 tables:
user
id --- name
posts
id --- userid --- text --- postdate
now want select users , every post they've made in past 15 minutes. want display every user didn't didn't make post matching conditions @ all.
i'm doing way:
$user_q = mysql_query("select * user"); while ($a = mysql_fetch_assoc($user_q)) { $post_q = mysql_query("select * posts userid=".$a['id']." , postdate >= date_sub(now(), interval 15 minute)"); //do information }
do have ideas how can put information in 1 query? doing many queries makes server running slow.
what want left outer join:
select u.*, p.* users u left outer join posts p on u.id = p.userid , p.postdate >= date_sub(now(), interval 15 minute);
the left outer join
keeps rows in first table. if nothing matches in second table, using condition, values null
fields.
edit:
if want limit 50 random users, can @ users
level:
select u.*, p.* (select u.* users u order rand() limit 50 ) u left outer join posts p on u.id = p.userid , p.postdate >= date_sub(now(), interval 15 minute);
the order rand()
makes them random. order -- name, date created, whatever. can leave order by
out , take 50 arbitrary rows returned database.
Comments
Post a Comment