I have a Query that works like a charm, but now I need to filter it by a value that is currently in a GROUP_CONCAT created field. i have learned that I can use HAVING to filter but I can’t find the syntax to use as HAVING groupconcatname LIKE '%6%' will find 6, 16, 26 etc .. I need to have the statement search for specific values so it can find “8” within the groupconcat containing 1,5,8,18,30,58 and not find 8 AND 18 AND 58 because i used a LIKE ‘%%’.
My Query (works right now .. but finds too many results based on a partial match of %6%):
SELECT offers.*, s.short_name AS sponsorName, s.logo AS sponsorLogo, GROUP_CONCAT( mn.title) titles,
GROUP_CONCAT( mo.`name`) metas, GROUP_CONCAT( om.meta_option) AS meta_ids
FROM offers
INNER JOIN offer_metas as om ON om.offer_id = local_ld_offers.id
INNER JOIN meta_options as mo ON om.meta_option = mo.id
INNER JOIN meta_names as mn ON mo.category = mn.category AND mo.cat_seq = mn.seq
LEFT JOIN sponsors AS s ON s.id=offers.sponsor
GROUP BY offers.id
HAVING meta_ids LIKE '%6%'
ORDER BY end_date ASC
I need to replace HAVING meta_ids LIKE '%6%' with something more akin to WHERE '6' IN meta_ids but when i try to replace the HAVING statement, with what seems like a reasonable attempt at a functioning WHERE, it ignores the fact that meta_ids is a valid variable/field to use in my clause and errors out.
Any recommendations?
Thanks,
Silver Tiger
UPDATE – Solved unless there is a more elegant way
Based on the recommendations from Thomas below I have updated the query and apparently I can search for as many individual values as I need by adding a line per option using the updated method as follows:
WHERE EXISTS( SELECT * FROM offer_metas AS om1 WHERE om1.meta_option = mo.id AND om1.meta_option = '23')
OR EXISTS( SELECT * FROM offer_metas AS om1 WHERE om1.meta_option = mo.id AND om1.meta_option = '16')
It isn’t clear exactly what is being asked here (some test inputs with expected outputs would help) but it doesn’t sound like you really need a Having clause. If you want to filter for values where say
om.meta_optionis “like” 8, then add a Where clause like so:Of course, this return rows where there exists
8,80,18and181. If you are looking for a specific value equal to8, then use:If what you seek is a series of values, then you can do something like:
Remember that the purpose of the Having clause to apply filters after the grouping and the Where clause applies filters prior to the grouping. In this case, it sounds like the filtering should happen prior to the grouping and thus the Where clause should be used.