I’ve been searching and couldn’t find any post like the problem I have:
I need to set an specific value in a "header", but since there’s no record, I can’t make it possible.
create table Det_TMZF_Authorizations
(id int, id_Det_TMZF int, authorization_format varchar(1));
Insert into Det_TMZF_Authorizations (id, id_Det_TMZF, authorization_format) values (1,1,'E');
Insert into Det_TMZF_Authorizations (id, id_Det_TMZF, authorization_format) values (2,2,'M');
SELECT
CASE dda.Authorization_Format
WHEN COALESCE(sum(dda.Authorization_Format), '0') THEN 'N'
ELSE 'Y'
END declare_certificate,
-- 'Y' declare_certificate,
dda.Authorization_Format authorization_format
FROM Det_TMZF_Authorizations dda
WHERE dda.id_Det_TMZF = 3
(Edit: tables with data and expected)
If I ask for id_Det_TMZF = 1 or 2, I have no problem setting "declare_certificate" = ‘Y’.
declare_certificate | id_Det_TMZF | authorization_format |
---|---|---|
Y | 1 | E |
Y | 2 | M |
but I need to set declare_certificate = ‘N’ when there’s no record.
I already tried "IFNULL(dda.Authorization_Format), ‘0’) THEN ‘N’" but got more errors than results.
I want this result:
declare_certificate | id_Det_TMZF | authorization_format |
---|---|---|
N | NULL | NULL |
2
Answers
You can use an
UNION
operation plus an aggregation with a little trick to solve this problem:The trick is to rely on the ASCII table ordering. Since
[0-9]
are always smaller in the ASCII table themax
operation will always get the rows with an ALPHA char on it. The query will always returns two rows one with the result of the original query and one from theUnion
operation, then we apply the aggregation which will take advantage of the ASCII ordering. If the original query has no rows on it, it will process the row from theUNION
.See it working in here: https://www.db-fiddle.com/f/teQhRGvnSh4vc1jAevRT8v/1
A
LEFT JOIN
to a single (dummy) row will ensure the result set to have at least one row.Your conditions must be in the
ON
clause in this case. If there are no rows matching the conditions, all rows from the right table (including primary key) will beNULL
. Check the PK forNULL
and you will know if the result has any rows at all.