简体   繁体   English

Mysql返回默认值,即使join不返回任何记录

[英]Mysql return a default value even if join does not return any records

I have 4 tables that I join by using this query below. 我通过以下查询使用联接的4个表。 Given my data below, it wont actually return any because there are no records in the TRANSACTION_LINE with a line object type value of 6. 给定我在下面的数据,它实际上不会返回任何值,因为TRANSACTION_LINE中没有行对象类型值为6的记录。

I want this query to return a default value of key_1 from EX_WORK, null line_Id, default value of 'OFF' on the TENDER_CODE if the query does not return any records. 我希望此查询从EX_WORK返回key_1的默认值,为null line_Id,如果查询不返回任何记录,则在TENDER_CODE上返回默认值'OFF'。

I already tried coalesce and ifnull but seemed that it did not work. 我已经尝试过合并和ifnull,但似乎没有用。 Can this be fixed by doing a left join instead of the inner? 是否可以通过左连接而不是内部连接来解决?

Thanks! 谢谢!

SELECT  w.key_1 as if_entry_no, 
           l.line_id as line_id, 
           o.object_export_code as tender_code
      FROM EX_WORK w,
           transaction_header h, 
           transaction_line l, 
           line_object o 
     WHERE w.key_1 = h.if_entry_no
       AND h.transaction_void_flag in (0,8)
       AND h.if_entry_no = l.if_entry_no
       AND l.line_object_type = 6
       AND l.line_action <> 55 
       AND (l.line_action <> 72 OR h.tender_total = 0)  
       AND l.line_object = o.line_object

EX_WORK
serial_no   key_1   
111         2879051 

TRANSACTION_HEADER
if_entry_no store_no transaction_void_flag tender_total
2879051     9500     0                     0

TRANSACTION_LINE
if_entry_no line_Id line_object_type line_object line_action
2879051     1       14               9109        38
2879051     2       1                9105        99
2879051     3       5                9501        98
2879051     4       11               9111        46

LINE_OBJECT
line_object line_object_type    resource_id object_export_code
9105        1                   5529        null
9109        1                   5533        null
9111        1                   5535        null
9501        1                   5709        null

Yes, you want a left join. 是的,您想要左联接。 Something like this: 像这样:

SELECT if_entry_no, line_id, ifnull(o.object_export_code, "OFF") AS tender_code
FROM (SELECT w.key_1 AS if_entry_no, l.line_id AS line_id, l.line_object
      FROM EX_WORK w,
           transaction_header h,
           transaction_line l,
           line_object o
      WHERE w.key_1 = h.if_entry_no
        AND h.transaction_void_flag IN (0, 8)
        AND h.if_entry_no = l.if_entry_no
        AND l.line_object_type = 6
        AND l.line_action <> 55
        AND (l.line_action <> 72 OR h.tender_total = 0)) s
       LEFT JOIN line_object o ON s.line_object = o.line_object;

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

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