Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: Can you pull results that match like 3 out of 4 expressions?

Tags:

mysql

Say I have a query like this:

SELECT * FROM my_table WHERE name = "john doe" AND phone = "8183321234" AND email = "[email protected]" AND address = "330 some lane";

But say I only need 3 out of the 4 to match, I know I can write a very long query with several ORs but I was wondering if there was a feature for this?

Thanks.

like image 201
JD Isaacks Avatar asked Apr 17 '09 15:04

JD Isaacks


2 Answers

SELECT
  * 
FROM 
  my_table 
WHERE 
  CASE WHEN name = "john doe"           THEN 1 ELSE 0 END +
  CASE WHEN phone = "8183321234"        THEN 1 ELSE 0 END +
  CASE WHEN email = "[email protected]" THEN 1 ELSE 0 END +
  CASE WHEN address = "330 some lane"   THEN 1 ELSE 0 END
  >= 3;

Side note: this will very likely not be using indexes efficiently. On the other hand, there will very likely be no indexes on these kinds of columns anyway.

like image 67
Tomalak Avatar answered Oct 24 '22 20:10

Tomalak


Holy overcomplexity, Batman.

SELECT * 
FROM my_table 
WHERE (
    (name = "john doe") +
    (phone = "8183321234") +
    (email = "[email protected]") +
    (address = "330 some lane")
) >= 3;
like image 36
chaos Avatar answered Oct 24 '22 20:10

chaos