Skip to content
Advertisement

SQL – Select records where columns include the keyword and have the same category

I’m working on a search bar. I have two fields category and input. If the user types the query and doesn’t select a category

I want to get all records matching the keyword. I’ve done it and it’s working perfectly.

Now If the user select a category with the keyword. I want get records where category is user’s selected category.

SELECT uid, title, posted FROM mytable WHERE title LIKE '%anna%' OR tags LIKE '%anna%' AND categories LIKE '3d29d6fdaf670c8df35b630e' AND status = 'active' ORDER BY id DESC

The query above doesn’t return records with the same category.

I have a categories column in mytable and there can be multiple categories

3d29d6fdaf670c8df35b630e, bd414a2c5860e6cba1794040ef46fdcb

like so

How can I do this?

Advertisement

Answer

You need to make proper use of parentheses here to get the correct logical order you intend:

SELECT uid, title, posted
FROM mytable
WHERE
    (title LIKE '%anna%' OR tags LIKE '%anna%') AND
    categories LIKE '3d29d6fdaf670c8df35b630e' AND
    status = 'active'
ORDER BY id DESC;

The version you had was actually using this WHERE clause:

WHERE
    title LIKE '%anna%' OR
    (tags LIKE '%anna%' AND
    categories LIKE '3d29d6fdaf670c8df35b630e' AND
    status = 'active')
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement