I’m lost with an MySQL query (running MySQL 5.0.88)
I have two tables, one with products from different brands, the other one with applications (= applications filter products, so not every application displays every product).
I’m trying to query to get a list of brands depending on the application the user is running like so:
SELECT p.brand_name
, p.id
, p.seller_id
, a.seller_id
, a.info
, a.name
, a.application_match_keys
FROM applications AS a
LEFT JOIN products AS p
ON a.seller_id = p.seller_id
AND p.brand_name IN ( <<QueryString: application_match_keys>> )
WHERE p.active = "1"
AND a.seller_id = "2222222222222"
GROUP BY p.brand_name
ORDER BY p.brand_name ASC
Problem is, once I do the left join I’m no longer getting correct results, so for example:
=== products ===
id brand_name seller_id
123 A John
111 A John
124 A John
999 B John
xx1 C John
=== applications ===
name seller_id info application_match_keys
red John foo A
blue John bar B,C
If the user is in application A, his brand list should only include brands from active products with corresponding match_keys (= A), so I would expect the query to return
p.brand_name application info
A red foo
But I’m always getting the correct brand name with mis-matched application data like so:
p.brand_name application info
A blue bar
Question:
Is there a way to query this in a single query, or do I have to query active products' brands with matching application key first and then loop/query again to get the application data I need? Must be possible in a single query, too?
Thanks for help!
EDIT:
Got it. This is how it works:
SELECT p.brand_name
, p.id
, p.seller_id
, a.seller_id
, a.info
, a.name
, a.application_match_keys
FROM applications AS a
LEFT JOIN products AS p
ON a.seller_id = p.seller_id
AND p.brand_name IN ( <<QueryString: application_match_keys>> )
AND FIND_IN_SET( a.application_match_keys, <<QueryString: application_match_keys>>) <> 0
WHERE p.active = "1"
AND a.seller_id = "2222222222222"
GROUP BY p.brand_name
ORDER BY p.brand_name ASC
Thank you very much!
how about using
FIND_IN_SET?