stickman Posted July 23, 2006 Share Posted July 23, 2006 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!!! Quote Link to comment https://forums.phpfreaks.com/topic/15421-select-with-2-tables/ Share on other sites More sharing options...
stickman Posted July 24, 2006 Author Share Posted July 24, 2006 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] Quote Link to comment https://forums.phpfreaks.com/topic/15421-select-with-2-tables/#findComment-62624 Share on other sites More sharing options...
fenway Posted July 24, 2006 Share Posted July 24, 2006 Well, first, proper JOIN syntax would be preferable; second, this doesn't satisfy your "at least" condition, since it will only retrieve those that match exactly. Quote Link to comment https://forums.phpfreaks.com/topic/15421-select-with-2-tables/#findComment-62641 Share on other sites More sharing options...
stickman Posted July 24, 2006 Author Share Posted July 24, 2006 The GROUP BY satisfies the at least. I dont need to return those rows or know how many rows there are, I just need to know if there is at least one row, but the user can have more. I'm not sure how to use the JOIN syntax. Quote Link to comment https://forums.phpfreaks.com/topic/15421-select-with-2-tables/#findComment-62644 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.