2012-01-30 130 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 = ?