MySQL Left Join没有产生预期的结果

时间:2011-10-06 20:28:50

标签: mysql sql left-join

我知道左连接有很多好的问题,但是我找不到与我的特定问题有关的内容。我为可能的重复主题道歉,但非常感谢帮助。

我有两张包含礼品卡销售的表格。我必须验证金额是否匹配。 我正在寻找帮助编写一个查询,即使表B中没有匹配的记录,也会返回表A中的所有内容。

表A

| id | business_date | am_pm | gift_cards_sold | 
================================================
 103 | 2011-10-06    | PM    | 175.03
 104 | 2011-10-06    | PM    | 135.03
 105 | 2011-10-06    | PM    | 250.74
 106 | 2011-10-06    | PM    | 180.44
 107 | 2011-10-06    | PM    | 150.10
 108 | 2011-10-06    | PM    | 130.00

表B

| id | business_date | am_pm | gift_cards_sold | 
================================================
 103 | 2011-10-06    | PM    | 100.03
 105 | 2011-10-06    | PM    | 250.74
 106 | 2011-10-06    | PM    | 180.44
 107 | 2011-10-06    | PM    | 150.10

到目前为止,这是我的查询(显然有问题)

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD
FROM A
LEFT JOIN B
USING (id)
WHERE A.am_pm = 'PM'
AND A.business_date = '2011-10-06'
AND B.business_date = '2011-10-06'
GROUP BY A.id
ORDER BY A.id ASC

结果如下:

| id | A_SOLD | B_SOLD | 
========================
 103 | 175.03 | 100.03
 105 | 250.74 | 250.74
 106 | 180.44 | 180.44
 107 | 150.10 | 150.10

正如您所看到的,存在ID为103的差异。但是,无论是否存在匹配,我都需要将结果显示为每个id。结果集是我期望使用内部联接。

4 个答案:

答案 0 :(得分:1)

你应该使用这样的东西:

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD
FROM A
LEFT JOIN B
USING (id)
WHERE A.am_pm = 'PM'
AND A.business_date = '2011-10-06'
AND (B.business_date = '2011-10-06' or B.business_date is null)
GROUP BY A.id
ORDER BY A.id ASC

答案 1 :(得分:1)

我不确定你为什么使用“group by”子句 - 这里不需要它,在大多数其他数据库中,这将是语法错误。

我假设你只需匹配id上的行。

这应该有效:

select A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD
 from A left join b on b.id = a.id
where A.business_date = '2011-10-06'  
  and A.am_pm = 'PM'
order by a.id

答案 2 :(得分:1)

只需将B.business_date = '2011-10-06'条件从WHERE移到ON子句即可。当您有LEFT加入时,关于第二个表的列(WHERE除外)的IS (NOT) NULL条件实际上会取消LEFT JOIN,然后它将充当INNER JOIN }。

SELECT A.id AS ID
     , A.gift_cards_sold AS A_SOLD
     , B.gift_cards_sold AS B_SOLD
FROM A
  LEFT JOIN B
    ON  B.id = A.id
    AND B.business_date = '2011-10-06'
WHERE A.am_pm = 'PM'
  AND A.business_date = '2011-10-06'
ORDER BY A.id

答案 3 :(得分:0)

问题在于B.business_date的where条件,它也应该允许null

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD
FROM A LEFT JOIN B ON A.id = B.id
WHERE A.am_pm = 'PM'
AND A.business_date = '2011-10-06'
AND (B.business_date = '2011-10-06' OR B.business_date is null )
ORDER BY A.id ASC