【问题标题】:Can I include a where clause before Inner join clause我可以在内部连接子句之前包含一个 where 子句吗
【发布时间】:2019-11-08 07:43:52
【问题描述】:

我有这个代码

$q = $conn->query("SELECT facultydetails.F_NAME,Paper_title from faculty inner join facultydetails on faculty.Fac_ID = facultydetails.Fac_ID where (paper_path = 'NULL' OR paper_path = '') and  (certificate_path = 'NULL' OR certificate_path = '') and (report_path = 'NULL' OR report_path = '') " );

现在我需要添加一个条件,用户将提供 id 并且只有应该选择与 id 相关的东西才能使用此代码

$q = $conn->query("SELECT facultydetails.F_NAME,Paper_title from faculty where facultydetails.Fac_ID='$FacID' inner join facultydetails on faculty.Fac_ID = facultydetails.Fac_ID where (paper_path = 'NULL' OR paper_path = '') and  (certificate_path = 'NULL' OR certificate_path = '') and (report_path = 'NULL' OR report_path = '') " ); 

在 php 中工作

【问题讨论】:

标签: php mysql


【解决方案1】:

您不能在内连接之前添加 where,但您可以将您的条件添加到 on 子句中,例如:

"SELECT facultydetails.F_NAME,Paper_title ".
"from faculty ".
"inner join facultydetails ".
"on (facultydetails.Fac_ID='$FacID') and (faculty.Fac_ID = facultydetails.Fac_ID) ".
"where (paper_path = 'NULL' OR paper_path = '') and  (certificate_path = 'NULL' OR certificate_path = '') and (report_path = 'NULL' OR report_path = '') "

或者您可以预先过滤您的教师表,例如:

"SELECT facultydetails.F_NAME,Paper_title ".
"from (select * from faculty where (facultydetails.Fac_ID='$FacID')) f ".
"inner join facultydetails ".
"on f.Fac_ID = facultydetails.Fac_ID ".
"where (paper_path = 'NULL' OR paper_path = '') and  (certificate_path = 'NULL' OR certificate_path = '') and (report_path = 'NULL' OR report_path = '') "

编辑:

在 SQL 中,在单个查询中的代码“高于”或“低于”某些其他部分并不能保证它在它之前执行。

【讨论】:

    【解决方案2】:

    不,你不能在内连接之前添加 where 子句。

    内连接的语法如下:

    SELECT column_list
    FROM t1
    INNER JOIN t2 ON join_condition1
    INNER JOIN t3 ON join_condition2
    ...
    WHERE where_conditions;
    

    【讨论】:

      【解决方案3】:
      SELECT facultydetails.F_NAME,Paper_title 
      from faculty 
      inner join facultydetails on faculty.Fac_ID = facultydetails.Fac_ID 
      where facultydetails.Fac_ID='$FacID' 
      AND (paper_path = 'NULL' OR paper_path = '') and  (certificate_path = 'NULL' OR certificate_path = '') and (report_path = 'NULL' OR report_path = '')
      

      【讨论】:

      • 一个SQL只能有一个where子句你可以像上面那样使用
      猜你喜欢
      • 1970-01-01
      • 2010-12-12
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2018-07-22
      • 2013-03-03
      相关资源
      最近更新 更多