简体   繁体   中英

In mySql, how can I ask: select this row from table 1 where x = column in table 2 or no rows in table 2

Could not find an answer here, only pieces... Specifically:

Table 1
  id, product

Table 2
  id, keyword, value

Given a list of keywords and values (array, json, anything), such as:

  year=1920
    model=R45-2
    color=green

For a given row in Table 1 matched by id, there may be no row in Table 2, or any number of them. Each will have a different keyword & value.

I need to return rows from Table 1 where there is either NO matching pair in Table 2, or EVERY keyword from my list matches its corresponding value in Table 2.

I'm aware that I can use IN, JOINS and sub-queries, but every solution I think of looks HORRIBLE (and may be a speed-hog). What is the fast, efficient, clean-reading way to do this? Remember, the 'list' provided may have none, one or n entries; Table 2 as well. NO match at all for a given keyword in Table 2 should allow Table 1 row through, or all in list matching; any keyword/value mismatch should invalidate that row from Table 1.

Good luck.

I think that group by and having can do what you want:

select t1.id, t1.product
from table1 t1
left join table2 t2 using (id)
group by t1.id, t1.product
having not max(
      (t2.keyword = 'year'  and t2.value <> '1920')
    + (t2.keyword = 'model' and t2.value <> 'R45-2')
    + (t2.keyword = 'color' and t2.value <> 'green')
) <=> 1

Here is what finally worked; seems simplest: (relevant sections only)

User wants color=green, size=small. So, number of terms is two.

SELECT ... LEFT JOIN (SELECT itemID, COUNT(itemID) AS filterCount FROM auctionExtras E WHERE (E.key = 'color' AND E.value = 'green') OR (E.key = 'size' AND E.value = 'small') [OR term clause n] GROUP BY itemID) as F on (...) WHERE (filterCount = [number of terms])

I THINK fairly quick on the subquery as ON restricts to an ID from the main query, and 'keys' in the joined file won't be evaluated at all unless you add them in to the WHERE. Everything indexed, and I doubt anyone will ever use more than five key/value pairs.

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