I have a relatively simple query.
SELECT DISTINCT
tA.id AS 'id'
//as pointed out, I could just select tB.value without the case here
,CASE WHEN tB.udf_id IN ('1')
THEN tB.value
END AS 'side'
FROM tableA tA
INNER JOIN tableB tB ON tA.id = tB.id
WHERE tB.udf_id IN ('1')
tableA
|id| date |
|--|----------|
|1 | 1/1/2023 |
|2 | 1/2/2023 |
|3 | 1/3/2023 |
tableB
|id|udf_id| value |
|--|------|---------|
|1 | 1 | right |
|1 | 2 | active |
|2 | 1 | left |
|2 | 2 | NULL |
|3 | 3 | right |
|3 | 3 | pending |
This will give me 1 row per "id" because of the WHERE clause.
Result Output
|id| value |
|--|---------|
|1 | right |
|2 | left |
|3 | right |
However, I now want to add another condition to what data gets returned. I only want to return results;
tB.value is not NULL when tB.udf_id=2
(pseudocode, I know this doesn't work this way)
So the new result output would look the same but drop id=2 because tb.value=NULLwhen tb.udf_id=2.
New Result Output
|id| value |
|--|---------|
|1 | right |
|3 | right |
I'm struggling on how to do this. Just adding another udf_id value creates multiple rows of results instead of the one, which I don't want. And I don't believe I can express my codition in the WHERE clause like that.
My assumption is that I need to do some sort of subquery?
1条答案
按热度按时间rekjcdws1#
Below code will check for
udf_id = '2'
without "joining" an extra set of records