简体   繁体   中英

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

i am running this SQL query:

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'

which returns both a.retail and b.cost if the row exists in call_costs_custom but if the row does not exist, i want to show just a.retail using the WHERE clauses for a. (call_costs) a. (call_costs)

From W3Schools:

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

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' 

You want an outer join, ie a join that keeps records from the first table even when there is no match in the second table. Use LEFT OUTER JOIN or short LEFT JOIN hence:

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';

Your explanation is not 100% clear but here is my attempt:

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' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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