Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Show records which meet 2 or more of multiple conditions

Tags:

sql

mysql

I have a MySQL table of many records. I am trying to find a way to show the records which meet more than one condition of a query. For example, if I had this table.

TABLE NAME: DATA

ID   contactid  flag        flag_type 
-----------------------------------
1     99         Volunteer   1 
2     99         Uploaded    2 
3    100         Via Import  3 
4    100         Volunteer   1  
5    100         Uploaded    2

with conditions such as:

WHERE (ID > 2) OR (flag = 'Uploaded') OR (flag_type = 1) ..etc..

The output would be where IDs 4 & 5 only would be returned.

like image 857
user2761030 Avatar asked Oct 19 '25 08:10

user2761030


1 Answers

You can count the number of conditions in MySQL and use this value:

where ((id > 2) +
       (flag = 'Uploaded') +
       (flag_type = 1)
      ) > 1

A boolean value of "true" is treated as 1 AND "false" is treated as 0. So, by adding up the values, you get the number of conditions that are met.

Often, you do this in an order by, to get the most matching first:

where id > 2 or flag = 'Uploaded' or flag_type = 1
order by ((id > 2) +
          (flag = 'Uploaded') +
          (flag_type = 1)
         ) desc;
like image 170
Gordon Linoff Avatar answered Oct 21 '25 23:10

Gordon Linoff