2

I would be forever in debt to the one person that can help me with this case / issue that I'm having:

There is a table with the following structure:

id(AI)| ColA | ColB   | ColC
-----------------------------
1     |1     | lorem  | ipsum
2     |1     | dolor  | sit
3     |0     | amet   | nula
...

I would like to set the columns to search in (ColB or ColC) based on the value in the ColA. For example (pseudo query):

  • select * from table if ColA = 1 then ColB like '%some_criteria%' else if ColA = 0 then (ColB like '%some_criteria%' and ColC like '%some_criteria%')

Basically, in the same one query:

  • if ColA has value '1' then search only in ColB
  • if ColA has value '0' then search in ColB and ColC

Let's say that ColB stores article titles and ColC stores articles descriptions. ColA stores articles types. So, if article type is 1, search only in title else, if article type is 0 then search in title and description.

Thank you in advance for your help!

Dacian
  • 33
  • 1
  • 4
  • Does this link help you? https://dba.stackexchange.com/questions/99218/select-column-value-based-on-two-values-in-another-column – Rohan Rao Dec 13 '19 at 04:11

1 Answers1

2

You could do it with conditions in the WHERE clause SQL Switch/Case in 'where' clause

SELECT *
FROM table
WHERE 
    (ColA = 1 AND ColB LIKE '%some_criteria%')
    OR
    (ColA = 0 AND (ColB LIKE '%some_criteria%' OR ColC LIKE '%some_criteria%'))

Also, a simple UNION would work as another example https://www.w3schools.com/sql/sql_union.asp

SELECT *
FROM table
WHERE ColA = 1 AND ColB LIKE '%some_criteria%'
UNION ALL
SELECT *
FROM table
WHERE ColA = 0 AND (ColB LIKE '%some_criteria%' OR ColC LIKE '%some_criteria%')

Note that UNION ALL would return duplicates if any were to occur, and just UNION returns distinct rows.

chrisbyte
  • 1,408
  • 3
  • 11
  • 18