I have a table like the following
------------------------- | aid | tid | dft | ------------------------- | 1 | 1 | Y | ------------------------- | 1 | 2 | N | ------------------------- | 2 | 3 | Y | ------------------------- | 3 | 4 | Y | ------------------------- | 3 | 5 | N | -------------------------
I want to query the table to get the tid out based on aid and tid but if the tid does not exist for that aid then it should return the default tid (identified by Y in the dft column).
I have tried the following which does not throw an error but returns NULL
SELECT
IF (
t1.tid IS NOT NULL,
t1.tid,
(
SELECT
t2.tid
FROM
table t2
WHERE
t2.aid = 1
AND t2.dft = 'Y'
)
) AS tid
FROM
table t1
WHERE
t1.aid = 1
AND t1.tid = 3
As that code is looking up tid 3 with aid 1 that doesn’t exist so should return tid of 1 as that is what is marked as Y in the dft column.
Can anybody help?
Try this:
If the combination of
aidandtidis unique then you can use this version: