mysql - 条件' on子句'在mysql中加入

时间:2014-10-04 14:11:27

标签: mysql

我尝试建立条件' on条款'在mysql连接中。

如果field1不为空,则应在' on claus'中使用 但如果为空,则应使用field2。

SELECT * FROM table1
JOIN table2

IF (field1!='') THEN (
    ON  table1.field1 = table2.field1
    AND table1.field3 = table2.field3
    )
ELSE (
    ON  table1.field2 = table2.field2
    AND table1.field3 = table2.field3
    )
END IF

有任何想法是否可以做到这一点?

编辑: 我忘了解释两个表都包含空字段,我试图阻止mysql使用这些字段进行连接,因为它提供了(非常)很多连接,所以我的想法应该更像这样:

SELECT * FROM table1
JOIN table2

IF (table1.field1!='' AND table2.field1!='') THEN (
    ON  table1.field1 = table2.field1
    AND table1.field3 = table2.field3
    )
ELSE (
    ON  table1.field2 = table2.field2
    AND table1.field3 = table2.field3
    )
END IF

3 个答案:

答案 0 :(得分:3)

请改为尝试:

SELECT * FROM table1 t1
LEFT JOIN table2 t2
LEFT JOIN table2 t3
on t1.Field1=t2.Field1 and t1.Field3=t2.Field3
on t1.Field2=t3.Field2 and t1.Field3=t3.Field3

然后使用条件从table2或table3中选择字段。

希望这会对你有所帮助。

修改

要选择正确的字段,请使用:

SELECT t1.*, IF(t2.field1 is null, t3.field1, t2.Field1) as Field1

答案 1 :(得分:0)

您应该考虑将INNER JOIN转换为LEFT JOIN,如其他答案所示,如

SELECT * FROM table1 t1
     LEFT JOIN table2 t2
     ON t1.field1 = t2.field1 AND t1.field3 = t2.field3
     LEFT JOIN table2 t22
     ON t1.field2 = t22.field2 AND t1.field3 = t22.field3

您也可以尝试下面的内容

SELECT t1.*
FROM table1 t1
  JOIN table2 t2
    ON t1.field1 = t2.field1 AND t1.field3 = t2.field3 
       OR t1.field2 = t2.field2 AND t1.field3 = t2.field3

答案 2 :(得分:0)

我认为你可以这样做:

SELECT * FROM table1 
JOIN table2 ON 
     (
        (table1.field1 = '' AND table1.field2 = table2.field2 AND table1.field3 = table2.field3) 
        OR 
        (table1.field1 != '' AND table1.field1 = table2.field1 AND table1.field3 = table2.field3)
     )

(注意:我不知道这种方法的效率如何)