Jump to content

Select with 2 tables


stickman

Recommended Posts

I dont know if this is possible, but I was wondering if there was a way to only select a user from table A if that user has at least one row in table B. Here is how I do it in PHP:

[code]
$query = "SELECT * FROM `table_a` ORDER BY `user`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
    $query2 = "SELECT * FROM `table_b` WHERE `user_id` = '{$row['id']}'";
    $result2 = mysql_query($query2);
    if(mysql_num_rows($result2)==0) {continue;}
    echo $row['user'];
    echo "<br>";
}
[/code]

That will output every user that has at least one row in table B. I was wondering if there was any way to do that with 1 SELECT statement?

Thanks in advance for any help!!!
Link to comment
Share on other sites

I figured it out. Here is my query for people who are asking the same question. I'm not sure if this is the proper way or not, but it works:

[code]SELECT * FROM `table_a` a, `table_b` b WHERE a.id = b.user_id GROUP BY a.user ORDER BY a.user[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.