How can I match (mysql) rows by one field and also another field that does not match
Say I have a MySQL table with 4 fields:
ID | ONE | TWO | THREE
I need to do a query that, in the end result, will show two rows. I need field 'ONE' to match. Both say 'w开发者_开发问答idget'.
Then, field 'TWO' of one row should match 'MFG' and the other to be anything except 'MFG'. For example:
ID | ONE | TWO | THREE
-----------------------
1 | WID | MFG | sthg
2 | WID | STR | stes
OK, maybe this will help..
This is the statement I have so far.
SELECT *
FROM cs_coupons
WHERE brand='Zantac'
AND product='Heartburn Relief 24ct +'
AND type='MFG'
UNION
SELECT *
FROM cs_coupons
WHERE brand='Zantac'
AND product='Heartburn Relief 24ct +'
AND type != 'MFG'
What I need to do is sort through all the rows checking each brand for these matches.
((SELECT * FROM mytable WHERE ONE='WID' AND TWO='MFG' LIMIT 1)
UNION
(SELECT * FROM mytable WHERE ONE='WID' AND TWO != 'MFG' LIMIT 1) );
first query returns one record with WIG & MFG, second query returns one record with WIG & !MFG. There you go.
But I think most probably you're misconstructing the scheme. You won't be sure that which record will be chosen if there are more than one records with WIG & MFG.
Maybe something like this:
SELECT *
FROM cs_coupons
WHERE ID IN (
SELECT MIN(ID) AS ID
FROM cs_coupons
WHERE type='MFG'
GROUP BY brand, product
UNION ALL
SELECT (MIN(ID) AS ID
FROM cs_coupons
WHERE type != 'MFG'
GROUP BY brand, product
) x
ORDER BY brand, product, type = 'MFG' DESC
?
精彩评论