2012-01-30 87 views
1

我试图在一个条件下将另一个表连接到另一个条件,然后将该表连接到另一个条件上的另一个表。你能做到这一点吗?如果是的话,那么正确的语法是什么?我一直在尝试这个,但它不起作用:Mysql:与多个'where'加入3个表?

$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(); 

欢呼声。

+0

您只能有一个'WHERE'子句,但是您可以在其中放置多个条件。请参阅您使用如何编写该数据库的文档,特别是在“JOIN”环境中。 – hakre 2012-01-30 16:47:38

回答

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

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 = ? 
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 = ?