0

I've got a MySQL table which contains 3 columns, the columns are named the following: TypeID, PropertyID, ValueID.

Let's say the table has the following rows:

| TypeID | PropertyID | ValueID |
| 45     | 266        | 736     |
| 46     | 266        | 736     |
| 50     | 266        | 736     |
| 52     | 266        | 736     |
| 50     | 229        | 628     |
| 52     | 229        | 628     |

I'm looking to select the TypeID when ValueID matches both 736 and 628 which is the case for both 50 and 52.

Please let me know if this needs explaining further.

1
  • 1
    Group by on TypeID, provide ValueId as IN clause and find distinct count of 2. Commented Aug 2, 2018 at 11:16

2 Answers 2

4

You want GROUP BY :

select TypeID
from table t
where ValueID in (736, 628)
group by TypeID
having count(*) = 2; 

If you have duplicate ValueID then you need COUNT(DISTINCT ValueID).

If you want to all columns then you can do JOIN :

select t.*
from table t inner join
     (select TypeID
      from table t
      where ValueID in (736, 628)
      group by TypeID
      having count(*) = 2
     ) tt 
    on tt.TypeID = t.TypeID;
Sign up to request clarification or add additional context in comments.

1 Comment

If I wanted to create a new table in MySQL with 3 columns (same as the previous table) to store the results in. How would I go about select TypeID, PropertyID, ValueID as I only want to group by TypeID?
0

You can use following query to fetch the records

select TypeID from table where ValueID=736 or ValueID=628
    group by TypeID
    having count(distinct ValueID) > 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.