sql query : perform a where in if condition

170 Views Asked by At

i've a situation like the following :

  • i've a long query that join a table
  • all the columns in joined tabled contain a column 'name'. in this table there are two names 'A' and 'B' (but can be C,D......Z, i don't know how many names we can have) and both of them have multiple rows, so i've n rows with name A and n rows with name B
  • sometimes, based on the user input, i need to join the entire table (with all the names) BUT only put some condition where the name is 'A' (for example).

so :

joint table myTable (it will take all the results A,B,C...) but if the name = 'A' then A.priority = A.userInput (for B,C... get them without additional conditions)

so, is there a solutions for this or i need to do multiple calls to the database ?

Thanks.

1

There are 1 best solutions below

2
On

I would use UNION ALL clause for this

SELECT *
  FROM TABLE1 T1
  JOIN TABLE2 T2
    ON T1.somecolumn = T2.somecolumn
  WHERE T2.name <> 'A'
UNION ALL
SELECT *
  FROM TABLE1 T1
  JOIN TABLE2 T2
    ON T1.somecolumn = T2.somecolumn
  WHERE T2.name = 'A' AND some condition