One alternative is to test a condition in an expression the SELECT list.
I think the simplest way to explain it would be by example. But I can't in good conscience post example code that is vulnerable to SQL Injection.
Current query:
SELECT a.*
FROM articles
WHERE a.`title` LIKE CONCAT('%', ? ,'%')
OR a.`description` LIKE CONCAT('%', ? ,'%')
OR a.`tags` LIKE CONCAT('%', ? ,'%')
ORDER
BY a.dateadded
To the current query, we can add expressions to the SELECT list. As an example:
SELECT IF( a.`title` LIKE CONCAT('%', ? ,'%') ,1,0) AS match_in_title
, IF( a.`description` LIKE CONCAT('%', ? ,'%') ,1,0) AS match_in_description
, IF( a.`tags` LIKE CONCAT('%', ? ,'%') ,1,0) AS match_in_tags
, a.*
FROM articles
WHERE a.`title` LIKE CONCAT('%', ? ,'%')
OR a.`description` LIKE CONCAT('%', ? ,'%')
OR a.`tags` LIKE CONCAT('%', ? ,'%')
ORDER
BY a.dateadded
For each row returned, the expression in the SELECT list is evaluated. The conditional test (LIKE
comparison) is evaluated to be either TRUE, FALSE or NULL. The MySQL IF
function will evaluate the first argument as a boolean, if that's true, it will return the second argument, elise it returns the third argument.
In this example, the expression returns a 1
if there's a match. Otherwise, it returns a 0
. There's lots of other choices for values we could return. We could also combine the conditions in a single expression, to return a single value.
And there are a lot of possible expressions that can include a conditional test. I've just used the MySQL IF
function. A more ANSI standards compliant expression could use CASE
, e.g.
SELECT CASE WHEN a.`title` LIKE CONCAT('%', ? ,'%')
THEN 1
ELSE 0
END AS match_in_title