开发者

select rows in mysql database based on associations in another table

I am using PHP and MySQL.

I have a tab开发者_JAVA百科le user_groups with the following fields

id, userID, groupID

A user can be associated with many groups, so if I selected from this table a particular userID then I could come up with several groupID's

I have another table group_messages with the following fields

id, groupID, message

If I want to select all of the messages from the group_messages table whose groupID is associated with a particular userID, how can I write this query? I first need to select all of the groupID's from the user_groups table where the userID is a particular id and then select all of the messages from the group_messages where the groupID is any that I have selected from the user_groups table.

Therefore, I can select all of the groupID's from the user_groups table by:

SELECT * FROM user_groups WHERE userID = '3'

This will return a range of groupID's

Then I need to select only those messages in the group_messages table where the groupID is within the set of numbers I have grabbed from the user_groups table.

Is there a way to do this with one query? I thought that maybe I could create an array of the groupIDs from the user_groups table and then dynamically with a foreach statement generate the sql query like:

$sql = "SELECT * FROM group_messages WHERE (";

foreach ($groupID_array as $v){
  $sql .= "(groupID = '$v')or";   
}
$sql = rtrim($sql, 'or');

$sql .= ")";

The problem with this method is that there could be thousands of groups a user is associated with, which would make this code run very slow and time out. Is there another way to do it with one query?


Use the IN operator:

SELECT * FROM group_messages WHERE groupID IN (1,2,3,4);

As 9000 mentioned below, you can make this in a single query like this:

SELECT * FROM group_messages 
  WHERE groupID IN (SELECT groupID FROM user_groups WHERE userID = '3')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜