简体   繁体   中英

Mysql how to filter results on multiple rows by 2 queries

I am trying to filter results where the relation is in multiple rows and so I need to first get the ID by matching a value and then use the query again to fetch value from another row for the retrieved value from the same table.

ID - MetaKey - MetaValue
142398 - _wc_checkout_add_on_id - 4
142398 - _wc_checkout_add_on_value - wife
142398 - _wc_checkout_add_on_label - Wife

So I get ID via matching key and value from row 1, now within the same query I want to get metavalue of 2nd and 3rd row to generate the final results, I am unable to do so at the moment.

Can anyone suggest please?

You can do it with sub query, eg:

SELECT *
FROM table
WHERE id IN (
 SELECT id FROM table WHERE metaKey = ? AND metaValue = ?
);

This will give you all the records belonging to that id. Now, if you don't want the first row in the result then you ca exclude itm, eg:

SELECT *
FROM table
WHERE id IN (
 SELECT id FROM table WHERE metaKey = ? AND metaValue = ?
)
AND metaKey <> ? AND metaValue <> ?;

something like this will work:

SELECT t2.*
FROM yourTAble t1
LEFT JOIN yourTable t2 
  ON t1.id = t2.id 
  AND NOT t2.MetaKey = t1.MetaKey
WHERE t1.id = 142398;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM