MySQL matching 2 out of 5 fields

前端 未结 3 1182
慢半拍i
慢半拍i 2021-01-04 07:23

In MySQL I\'m trying to select any row that matches at least 2 fields of the provided data

Eg. I have been given firstName, lastName, dob, website, email and I want

相关标签:
3条回答
  • 2021-01-04 08:04
    SELECT
    (CASE WHEN Field1 = Value1 THEN 1 ELSE 0 END
    +CASE WHEN Field2 = Value2 THEN 1 ELSE 0 END
    ...
    +CASE WHEN FieldN = ValueN THEN 1 ELSE 0 END
    )
    AS Conditions
    From YourTable
    WHERE Conditions >= (Min_Number_Of_Fields)
    
    0 讨论(0)
  • 2021-01-04 08:15

    You could count up the matching expressions. MySQL returns 1 for true and 0 for false.

    WHERE (FirstName = ?) + (LastName = ?) + (... = ?) > 2
    

    You can also order using this as well. You will want to sort descending to ensure that the higher matches appear first.

    ORDER BY ((FirstName = ?) + (LastName = ?) + (... = ?)) DESC
    
    0 讨论(0)
  • 2021-01-04 08:15

    As a'r's answer recommended, you can add together values. If you want to use this for ranking, you might not include it in the where clause as he did.

    SELECT *, ((firstName = @inputFirst) + (lastName = @inputLast) + (dob = @inputDob) + (website = @inputWebsite) + (email = @inputEmail)) as Matches
    FROM mytable
    HAVING Matches > 1
    ORDER BY Matches DESC
    

    I don't have access to a mysql db to test this syntax at the moment, but I believe it should work properly.

    0 讨论(0)
提交回复
热议问题