从两个表中选择的SQL查询 - 如果另一个表中没有表,则从一个表返回结果

时间:2016-05-13 18:43:01

标签: mysql sql

我正在运行此SQL查询:

SELECT a.retail, b.cost 
from call_costs a, call_costs_custom b 
WHERE a.sequence = b.parent 
 AND a.sequence = '15684' 
 AND b.customer_seq = '124'

如果a.retail中存在该行,则会返回b.costcall_costs_custom,但如果该行不存在,我只想使用{{1}显示a.retail } WHERE

的子句

3 个答案:

答案 0 :(得分:2)

来自W3Schools:

  

LEFT JOIN关键字返回左表(table1)中的所有行,   使用右表(table2)中的匹配行。结果为NULL   在没有匹配的情况下在右侧。

SELECT 
    a.retail,
    b.cost 
FROM 
    call_costs a
LEFT JOIN 
    call_costs_custom b 
        ON 
    a.sequence = b.parent 
        AND
    b.customer_seq = '124'
WHERE 
    a.sequence = '15684' 

答案 1 :(得分:1)

您需要一个外部联接,即即使第二个表中没有匹配项也会保留第一个表中的记录的联接。请使用LEFT OUTER JOIN或缩短LEFT JOIN

select cc.retail, ccc.cost 
from call_costs cc
left join call_costs_custom ccc on ccc.parent = cc.sequence and ccc.customer_seq = '124'
where cc.sequence = '15684';

答案 2 :(得分:0)

您的解释并非100%明确 但这是我的尝试:

SELECT COALESCE(b.cost,a.retail)
FROM call_costs a
LEFT JOIN call_costs_custom b 
ON a.sequence = b.parent 
  AND b.customer_seq = '124'
WHERE a.sequence = '15684'