简体   繁体   English

跳过多个表中的内部联接mysql查询

[英]Skipping inner joins in multiple tables mysql query

I built a large script with several inner joins working as "conditions" (instead of using WHERE clauses). 我构建了一个大型脚本,其中包含多个作为“条件”的内部联接(而不是使用WHERE子句)。 As a sample: 作为示例:

SELECT T1.*
FROM Table1 T1
    INNER JOIN Table2 T2
        ON T1.id = T2.id
    INNER JOIN Table3 T3
        ON T2.id = T3.id
    INNER JOIN Table4 T4
        ON T1.id = T4.id

etc... 等等...

Under certain conditions I need to skip one or several inner joins. 在某些情况下,我需要跳过一个或几个内部联接。 Till now, I had to duplicate the script commenting out the lines with the joins I don't need. 到现在为止,我不得不重复编写脚本,用不需要的连接注释掉行。 Would it be any way to work with variables or IF clauses to skip a join, or at least a "select all" way? 使用变量或IF子句跳过联接是否有任何方法,或者至少是“全选”方法?

Assuming php: 假设php:

$SQL = "
SELECT T1.*
FROM Table1 T1
    INNER JOIN Table2 T2
        ON T1.id = T2.id" . ($variable1 == x ? " OR TRUE=TRUE" : "") . "
    INNER JOIN Table3 T3
        ON T2.id = T3.id" . ($variable2 == y ? " OR TRUE=TRUE" : "") . "
    INNER JOIN Table4 T4
        ON T1.id = T4.id" . ($variable3 == z ? " OR TRUE=TRUE" : "")

But I'm sure you should rather build the query dynamically: 但是我确定您应该动态地构建查询:

$SQL = "
SELECT T1.*
FROM Table1 T1";

if ($variable1 == x) {
    $SQL .= " INNER JOIN Table2 T2 ON T1.id = T2.id";
}

if ($variable2 == y) {
    $SQL .= " INNER JOIN Table3 T3 ON T2.id = T3.id";
}

if ($variable3 == z) {
    $SQL .= " INNER JOIN Table4 T4 ON T3.id = T4.id";
}

etc. with all your joins. 等您的所有加入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM