繁体   English   中英

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

[英]sql query selecting from two tables - return results from one table if there are none in the other table

我正在运行此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'

如果行存在于call_costs_custom ,则返回a.retailb.cost但如果该行不存在,我想使用WHERE子句显示a.retail a. (call_costs) a. (call_costs)

来自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' 

您需要一个外部联接,即即使第二个表中没有匹配项也会保留第一个表中的记录的联接。 使用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';

你的解释不是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' 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM