简体   繁体   中英

Mysql select all rows meeting given criteria and other rows with same ID as the selected rows

Say I have this table:

在此处输入图片说明

The table has lots of rows in it, with DimCombinationID identifying rows that belong to the same group of rows.

I want to do a select with a where like: where (Dimension = 1 AND DimensionValue = 13) AND (Dimension = 5 AND DimensionValue = 15) which should retrieve all rows that have a DimCombinationID of 22 and 56 because they meet both requirements:

在此处输入图片说明

I tried all sorts of things but this explains most what I wrongly get:

Select DimCombinationID from TESTDimCombinations where (DimID = 1 AND DimValueID = 13) OR (DimID = 5 AND DimValueID = 15)

This will get DimCombinationIDs 22, 39 and 56. So all. While only 22 and 56 meet both criteria and 39 should not be in the response of the db.

Once I only have the desired 22 and 56, I want to wrap this query into an outer query which gets all columns for all rows which have DimCombinationID 22 or 56.

I think I need to do something with having or having count but I can't seem to figure it out.

Any help or thoughts about how to do this would be greatly appreciated.....I can't wrap my head around this one.

Thanks in advance!

With this:

select *
from TESTDimCombinations
where DimCombinationID in (
  select DimCombinationID 
  from TESTDimCombinations
  where (DimID = 1 AND DimValueID = 13) OR (DimID = 5 AND DimValueID = 15)
  group by DimCombinationID 
  having count(*) = 2
);

The subquery:

select DimCombinationID 
from TESTDimCombinations
where (DimID = 1 AND DimValueID = 13) OR (DimID = 5 AND DimValueID = 15)
group by DimCombinationID 
having count(*) = 2

gets the DimCombinationID s 22 and 56.
See the demo .
Results:

| DimCombinationID | DimID | DimValueID |
| ---------------- | ----- | ---------- |
| 22               | 1     | 13         |
| 22               | 2     | 9          |
| 22               | 5     | 15         |
| 22               | 2     | 2          |
| 56               | 1     | 13         |
| 56               | 2     | 17         |
| 56               | 5     | 15         |
| 56               | 2     | 51         |

I see no functional difference between the accepted answer and the following:

SELECT DISTINCT x.*
  FROM TESTDimCombinations x
  JOIN TESTDimCombinations y
    ON y.DimCombinationID = x.DimCombinationID 
 WHERE (DimID = 1 AND DimValueID = 13) 
    OR (DimID = 5 AND DimValueID = 15)

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