Mysql:加入3个表以及多个'where'?

时间:2012-01-30 16:46:11

标签: php mysql database

我试图在一个条件下将一个表连接到另一个表,然后在另一个条件下将表连接到另一个表。你能做到这一点,如果是这样,那么正确的语法是什么?我一直在尝试这个,但它不起作用:

$check = $members->prepare("select users.fname, users.lname, groups.groupid, attributes.max 
    from users 
    JOIN groups 
         on users.user_id = groups.userid 
    where groups.userid = ? 
    LEFT JOIN attributes 
         on users.user_id = attributes.userid 
    where attributes.groupid = ?");
$check->bind_param('ss', $_SESSION['token'][1], $which_group);
$check->execute();

欢呼声。

3 个答案:

答案 0 :(得分:2)

attributes.groupid的测试必须是LEFT JOIN上的连接条件的一部分。试图在WHERE子句中测试这个条件会强制LEFT JOIN的行为就好像它是一个INNER JOIN。

select users.fname, users.lname, groups.groupid, attributes.max 
    from users 
        JOIN groups 
            on users.user_id = groups.userid 
        LEFT JOIN attributes 
            on users.user_id = attributes.userid 
                and attributes.groupid = ?
    where groups.userid = ? 

答案 1 :(得分:2)

只需使用........ AND

$check = $members->prepare("select users.fname, users.lname, groups.groupid, attributes.max 
    FROM users 
    JOIN groups 
         ON users.user_id = groups.userid 
         AND groups.userid = ? 
    LEFT JOIN attributes 
         ON users.user_id = attributes.userid 
         AND attributes.groupid = ?

答案 2 :(得分:0)

如果您所指的条件是文字而且与联接表没有任何关系,请将它们合并到一个where子句中。

select users.fname, users.lname, groups.groupid, attributes.max
from users
   JOIN groups 
        on users.user_id = groups.userid 
    LEFT JOIN attributes 
        on users.user_id = attributes.userid 
where groups.userid = ? and attributes.groupid = ?