0

I started out with a question in this thread: Need SQL guru for a complex query

I now have that solved (thanks to SO), but now need to extract a bit more data.

Let's say I have a query that joins 2 other tables, where criteria in each of the three tables can cause a row to be added to the result set. Something like:

    SELECT a.*
    FROM tableA a
    LEFT JOIN tableB b on a.b_id = b.id
    LEFT JOIN tableC c on a.c_id = c.id
    WHERE a.creator_id = 5 OR b.is_active = 1 OR c.can_attend = 1

Whatever the data is... basically what I need to do is determine, for each row in the result set, which criteria allowed it in. Was it because creator_id was 5, or because it was active, etc.

From this overly simplified example, you could say just look at the data, but notice the data for tables b and c are not being returned, and note that there are a variety of ways in which the join may add the row to the result set.

What I am looking for, I think, is a way to inject a value when a row is added to the result set, or something to that effect. Will make more sense if you look at the accepted answer in the linked question above.

Thanks for any input!

4

1 回答 1

1

You can do this using a case statement:

SELECT a.*,
       (case when b.id is not null and c.id is not null then 'BOTH'
             when b.id is not null and c.id is null then 'B'
             when b.id is null and c.id is not null then 'C'
             else 'A'
        end) as WhereFrom
FROM tableA a
LEFT JOIN tableB b on a.b_id = b.id
LEFT JOIN tableC c on a.c_id = c.id
WHERE a.creator_id = 5 OR b.is_active = 1 OR c.can_attend = 1
于 2012-10-25T21:46:58.710 回答