1

I don't know if this question has been asked previously also. If so please direct me to the link.

I have a table that has three columns name, type and date. Type can only be 4 values A, B, C and D

I want to fetch all those records which are of type A, B or C but the condition is that it should only fetch if the same name also has a type of D.

e.g. lets consider this table

Name      type    Date 
abc        A       5/7
abc        B       6/7
abc        D       7/7

xyz        A       5/7
xyz        D       6/7

lmn        A       5/7
lmn        B       6/7
lmn        C       7/7

So the deal here I need the following result set

ABC 5/7
ABC 6/7
XYZ 5/7

Because ABC and XYZ has a type D the other records of ABC and XYZ are shown. Since lmn does not have a type D it's not included in the result set.

3 Answers 3

3

To test if a record exist, you can simply use where exists :

select * from mytable t1 where exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);

That's probably self explanatory but here's a reference : http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

If you want to exclude the D records, you do this :

select * from mytable t1 where t1.type<>"D" and exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);
Sign up to request clarification or add additional context in comments.

2 Comments

I believe this would return 3 records for ABC and 2 records for XYZ.
I reread the requirement and you're right. I edited my answer by adding a second query, that's a minor adjustment.
1

Try this:

SELECT Name, Date
FROM MyTable as mt
WHERE type != 'D'
AND EXISTS
(
   SELECT * FROM MyTable as mt2
   WHERE mt2.type = 'D' and mt2.name = mt.name
)

You are selecting all records where type is not equal to D and that have a record with a matching name where type IS equal to D

Comments

0
create view all_D as select name from your_table where type=D
select * from your_table where type<>D and name in (select * from all_D) 

You could even make it such that instead of having that view you jut put that query in the brackets after "not in"

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.