Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted conditions in the WHERE clause of a SQL statement

Tags:

sql

mysql

where

I want to search for records where a particular field either STARTS WITH some string (let's say "ar") OR that field CONTAINS the string, "ar".

However, I consider the two conditions different, because I'm limiting the number of results returned to 10 and I want the STARTS WITH condition to be weighted more heavily than the CONTAINS condition.

Example:

SELECT *
FROM Employees
WHERE Name LIKE 'ar%' OR Name LIKE '%ar%'
LIMIT 10

The catch is that is that if there are names that START with "ar" they should be favored. The only way I should get back a name that merely CONTAINS "ar" is if there are LESS than 10 names that START with "ar"

How can I do this against a MySQL database?

like image 821
Stephen Stchur Avatar asked Feb 17 '11 23:02

Stephen Stchur


People also ask

What can be the condition in WHERE clause in a SQL query?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.

Can we use multiple conditions in WHERE clause in SQL?

You can use the OR condition in the WHERE clause to test multiple conditions where the record is returned if any one of the conditions are met. This example uses the WHERE clause to define multiple conditions, but instead of using the AND condition, it uses the OR condition.

How many conditions can a WHERE clause contain?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.

Which operators are used in WHERE clause in SQL?

The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause. The NULL operator is used to compare a value with a NULL value.


1 Answers

You need to select them in 2 parts, and add a Preference tag to the results. 10 from each segment, then merge them and take again the best 10. If segment 1 produces 8 entries, then segment 2 of UNION ALL will product the remaining 2

SELECT *
FROM
(
SELECT *, 1 as Preferred
FROM Employees
WHERE Name LIKE 'ar%'
LIMIT 10
UNION ALL
SELECT *
FROM
(
    SELECT *, 2
    FROM Employees
    WHERE Name NOT LIKE 'ar%' AND Name LIKE '%ar%'
    LIMIT 10
) X
) Y
ORDER BY Preferred
LIMIT 10
like image 81
RichardTheKiwi Avatar answered Oct 06 '22 13:10

RichardTheKiwi