Mysql OUTER JOIN语法

时间:2014-04-15 20:10:08

标签: mysql

我的表格如下

productsA : name,price

productsB : name,date,price,...

目前,productsB包含了一个产品A的子集,具有今天的日期(试图简化,我知道我缺少的信息,并且能够理清其余部分)。

如果今天的产品B中没有记录,我想从产品A中选择所有产品。为简化起见,我们假设date ='2014-04-15'(已修复)。

我试过了:

SELECT a.*
FROM productsA AS a 
LEFT OUTER JOIN productsB as b on a.name = b.name AND b.date != '2014-04-15'

但它不起作用......

我试图简化并删除日期参数,但无论我如何尝试,我最终得到了整个产品表:

SELECT a.*
FROM productsA AS a 
LEFT OUTER JOIN productsB AS b ON a.name = b.name

一定很简单,但我被困住了(我把所有错误的尝试都饶了你)......任何人,帮忙吗?

1 个答案:

答案 0 :(得分:2)

要在a中查找b中没有相关记录的内容,主要是您需要使用NULL查找LEFT JOIN值。

SELECT
  a.*
FROM
  productsA AS a
  /* Your joining condition was almost correct- you need records equaling the date... */
  LEFT JOIN productsB AS b ON a.name = b.name AND b.date = '2014-04-15'
WHERE
  /* NULL returned for b means no match */
  b.name IS NULL

注意:如果该列上的DATE类型正确,您还可以在b.date = CURDATE()子句中使用ON ...