2

我正在处理一个查询,其中我有三个要加入的表,但是第三个表可能有也可能没有相关记录。

我目前有:

  SELECT table1.val, table2.val, table.3.val 
  FROM
      table1
      LEFT JOIN table2
          ON table1.val = table2.val
      LEFT JOIN table3 
          ON table.3.val = table2.val
  WHERE
      table1.name = "name" 
      AND table3.name = 'certain name'
  ORDER BY table1.val ASC

我怎样才能写这个,以便如果'certain name'不存在,则从and子句table3中省略该部分?我实际上选择了更多字段,但这应该足以说明问题。WHERESELECT

4

1 回答 1

1

如果您的意思是结果表单table3应该只可见,如果table3.val等于table2.valANDtable3.name应该等于'certain name',那么这将适合您:

SELECT table1.val, table2.val, table.3.val 
FROM table1
LEFT JOIN table2
ON table1.val = table2.val
LEFT JOIN table3 
ON table.3.val = table2.val AND table3.name = 'certain name'
WHERE table1.name = "name" 
ORDER BY table1.val ASC

毕竟,这LEFT JOIN是为了……

于 2012-10-21T20:33:50.517 回答