1

我有一个看起来像这样的查询:

SELECT 'asdf', '123' ...
FROM table1

LEFT JOIN table2
on
(
    condition1
)

LEFT JOIN table3
on
(
    condition2
)

where
(
    main_condition
)

现在的问题是,我也需要有条件地包含table1。我试过这个:

..
..
FROM table1
on
(
    new_condition
)
..
..

但这行不通。请帮忙。


编辑(新发现):在这篇文章(http://blog.sqlauthority.com/2010/07/20/sql-server-select-from-dual-dual-equivalent/)中,我发现了这段代码:

SELECT 1 as i, f.bar, f.jar FROM dual LEFT JOIN foo AS f on f.bar = 1 WHERE dual.dummy = ‘X’
UNION
SELECT 2 as i, f.bar, f.jar FROM dual LEFT JOIN foo AS f on f.bar = 2 WHERE dual.dummy = ‘X’

我确定这与我正在尝试做的事情没有直接关系,但是JOIN桌子可以DUAL喜欢这样吗?

4

5 回答 5

3

虚拟表:

首先从虚拟表中选择一条记录。dual就是这样一个表,它内置在 MySQL 中用于这个确切的目的。我包裹dual在一个子选择中,因为 MySQL 显然不允许左加入反对它。

SELECT 'asdf', '123' ...
FROM 
  (select 1 from dual) d
LEFT JOIN table1
on(
  new_condition
)
LEFT JOIN table2
on
(
    condition1
)

LEFT JOIN table3
on
(
    condition2
)

全(外)连接

另一种解决方案虽然不同,但使用 a full joinor full outer join,它类似于 aleft joinright join组合。这是完全不同的,尽管您可以获得非常相似的结果:

select
  *
from
  table1
  full outer join table2 on joincondition.

在上面的查询中,将返回两个表中的所有记录,即使两个表中都不存在匹配的记录。

于 2013-07-15T18:37:10.637 回答
1

感谢您参与讨论。我找到了答案。这真的很简单:

SELECT temp_table.* FROM
    (SELECT 'asdf', '123' ... FROM DUAL) temp_table
LEFT JOIN table1
on
(
    new_condition
)

LEFT JOIN table2
on
(
    condition1
)

LEFT JOIN table3
on
(
    condition2
)

where
(
    main_condition
)

有趣的问题。也许这次我应该喜欢我自己的问题:)

于 2013-07-15T19:08:41.987 回答
0

你不能在 ON 子句中创建这个新条件

on 子句只是你加入的时候,但你可以在 where 子句中添加这个新条件

例子

    where
 (
main_condition
 )
  AND
 (
  new condition 
 )

编辑:

试试这个

 SELECT 'asdf', '123' ...
 FROM (select 'asdf', '123' ... FROM table1 WHERE new_condition ) t
                                                      ^^--your new condition here
 LEFT JOIN table2
 on
 ........

EDIT2:如果你的新条件可能是错误的,你可以做一个 if 语句

    where
  (
 main_condition
 )
 AND
 (
  if(new condition is something , do something , else do something else) 
 )

编辑3:

 SELECT 'asdf', '123' ...
 FROM (select 'asdf', '123' ... FROM table1 where main condition
       UNION 
      select 'asdf', '123' ... FROM table1 WHERE new_condition ) t
                                                  ^^--your new condition here
 LEFT JOIN table2
 on
 ........
于 2013-07-15T18:35:29.280 回答
0

您需要在on第一次连接的子句中包含条件:

SELECT 'asdf', '123' ...
FROM table1 LEFT JOIN
     table2
     on condition1 AND new condition LEFT JOIN
     table3
     on condition2
where main_condition

使用where从句时left join要小心。通常,您希望将这些条件移动到on子句中,因为它们可能会无意中撤消左外连接的效果(将其变成inner join)。

于 2013-07-15T18:40:15.887 回答
0

迄今为止,我对评论的最佳猜测。

SELECT 'asdf', '123' ...
FROM table1
FULL OUTER JOIN table2  --NOTE THE FULL OUTER here  all records in table 2 and only those that match in table 1
on
    condition1 AND
    new_condition=True
LEFT JOIN table3
on
(
    condition2
)

where
(
    main_condition
)
于 2013-07-15T21:04:00.647 回答