0

I'm working in one scenario where I need to display few records from the table in which id does not exist in the list.

SELECT * FROM contract 
WHERE `id` NOT IN ( 
    CASE 
        WHEN type = 1 THEN '159,154' 
        WHEN type = 2 THEN '' 
        WHEN type = 3 THEN '' 
    END 
) 
ORDER BY id DESC 

Over here you can see that if contract type = 1 then the result should not display 159 & 154 records from the table. But 154 number record is also coming in the result which should not.

Any help appreciated!

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Pratik Patel
  • 131
  • 1
  • 3
  • 12

3 Answers3

1
...WHERE (type = 1 AND id NOT IN('159','154')) 
OR   (type = 2 AND id !='') 
OR   (type = 3 AND id !='') 

Remove the quotes if the id is numeric so you can use a possible index.

Mihai
  • 26,325
  • 7
  • 66
  • 81
0

Use MySQL INSTR() function as shown below:

SELECT * FROM contract 
WHERE INSTR(IF(type = 1, '159,154',''),`id`)<0
ORDER BY id DESC;
cdaiga
  • 4,861
  • 3
  • 22
  • 42
0

I think this would work:

SELECT * FROM contract 
WHERE (type = 1 AND id NOT IN ('159','154')) OR
    (type IN (2,3) AND id != '')
ORDER BY id DESC 
A. Colonna
  • 852
  • 7
  • 10