很多WHERE条件mysql

时间:2012-05-27 00:46:24

标签: mysql join where

我有以下代码可以执行我想要的操作。但是我需要第二个where表格项目中接受的列等于是的条件。我不知道如何将其输入到我当前的连接中,因为用户表的位置。

$query_Name = "SELECT u.Student_Surname, u.Student_Forename, Project_Title, Project_id
FROM users u
INNER JOIN projects p2 ON u.id = p2.Project_Lecturer
INNER JOIN project_course pc ON p2.Project_id = pc.Proj_id
INNER JOIN courses c ON pc.Cour_id = c.Course_id
INNER JOIN users u2 ON c.Code = u2.Course
WHERE u2.Username = ".$_SESSION['MM_Username']." 
ORDER BY Project_id ASC" ;

4 个答案:

答案 0 :(得分:1)

$query_Name = "SELECT u.Student_Surname, u.Student_Forename, Project_Title, Project_id  
 FROM users u
 INNER JOIN projects p2 ON u.id = p2.Project_Lecturer
 INNER JOIN project_course pc ON p2.Project_id = pc.Proj_id
 INNER JOIN courses c ON pc.Cour_id = c.Course_id
 INNER JOIN users u2 ON c.Code = u2.Course
 WHERE u2.Username = ".$_SESSION['MM_Username']." AND p2.Accepted = 'yes'
 ORDER BY Project_id ASC" ;

答案 1 :(得分:1)

WHERE u2.Username = ".$_SESSION['MM_Username']."  AND p2.Accepted = 'yes'

或者你可以使用

INNER JOIN projects p2 ON u.id = p2.Project_Lecturer AND p2.Accepted = 'yes'

第二种选择可能更快,但取决于其他事情

答案 2 :(得分:0)

WHERE实际上适用于所有连接表,因此您明确说明了您在WHERE子句中使用的表,否则如果查询不明确,查询将无效。

所以,你使用:

WHERE
u2.Username = ".$_SESSION['MM_Username']." -- this is for the u2 table
AND
p2.Accepted = 'yes' -- this is for p2 table

您只需使用AND在此处添加更多逻辑。所以,整个查询将是:

$query_Name = "SELECT u.Student_Surname, u.Student_Forename, Project_Title, Project_id  
 FROM users u
 INNER JOIN projects p2 ON u.id = p2.Project_Lecturer
 INNER JOIN project_course pc ON p2.Project_id = pc.Proj_id
 INNER JOIN courses c ON pc.Cour_id = c.Course_id
 INNER JOIN users u2 ON c.Code = u2.Course
 WHERE u2.Username = ".$_SESSION['MM_Username']." AND p2.Accepted = 'yes'
 ORDER BY Project_id ASC" ;

答案 3 :(得分:0)

在where子句中添加AND运算符。

$query_Name = "SELECT u.Student_Surname, 
                      u.Student_Forename, 
                      Project_Title, 
                      Project_id  
               FROM users u INNER JOIN projects p2 
                       ON u.id = p2.Project_Lecturer
                    INNER JOIN project_course pc 
                       ON p2.Project_id = pc.Proj_id
                    INNER JOIN courses c 
                       ON pc.Cour_id = c.Course_id
                    INNER JOIN users u2 ON c.Code = u2.Course
               WHERE u2.Username = ".$_SESSION['MM_Username']." 
                     AND p2.Accepted = 'yes'
               ORDER BY Project_id ASC" ;