如果记录存在,则添加WHERE子句

时间:2012-10-21 20:26:15

标签: mysql left-join exists

我正在进行查询,其中我有三个表要加入,但第三个表可能有也可能没有相关记录。

我目前有:

  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'table3中不存在WHERESELECT和{{1}}条款中省略了该部分?我实际上选择了几个字段,但这应该充分证明了这个问题。

1 个答案:

答案 0 :(得分:1)

如果您的意思是结果表单table3应该只显示,table3.val等于table2.val并且table3.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的目的......