0

I need to verify 2 columns but sometimes the second one will be empty then i need to verify the second column just if it's not empty otherwise it will just verify the first one

SELECT * 
FROM table 
WHERE column1 = $_GET['id'] 
and column2 IS NOT NULL = $_GET['id']
Declan_K
  • 6,726
  • 2
  • 19
  • 30
Eddie D.
  • 145
  • 3
  • 12
  • Are you saying the one or the other columns might be NULL and whichever is NOT NULL is the one you need the data from? – DevlshOne Sep 13 '13 at 19:15
  • Do you want resluts that have col2 as NOT NULL or col2 = $_GET['id']? You can't apply both those conditions in a single statment like that. (col2 = $_GET['id'] will automatically filter out NULLS) – Declan_K Sep 13 '13 at 19:17
  • the second column needs to be verified just if it's not null otherwise it must be ignored @Declan_K – Eddie D. Sep 13 '13 at 19:19
  • @EddieD. I have no idea what your comment means – Declan_K Sep 13 '13 at 19:20
  • it would be like this `if(column1 == $id and !empty($column2) == $id)` but in SQL @Declan_K – Eddie D. Sep 13 '13 at 19:23
  • In that case `column1 = $_GET['id'] and column2 = $_GET['id']` will work as that automatically excludes NULLS – Declan_K Sep 13 '13 at 19:24
  • not exactly.. because if column2 is empty it would be like this `if($column1 == $id)` the second one should be ignored @Declan_K – Eddie D. Sep 13 '13 at 19:27
  • Then Gordon's answer is the correct one. – Declan_K Sep 13 '13 at 19:28

2 Answers2

3

Is this the logic you want?

SELECT *
FROM table
WHERE column1 = $_GET['id'] and
      (column2 IS NULL or column2 = $_GET['id']);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0
SELECT IF(column1 IS NULL, column2, column1)
FROM table 
WHERE column1 = $_GET['id'] OR column2 = $_GET['id']
DevlshOne
  • 8,357
  • 1
  • 29
  • 37