Question

TABLE A:

dvdID.......dvdTitle

d01..........Avenger

d02..........Avenger

d03..........Spiderman

TABLE B:

rentID.......dvdID

r01...........d01

r02...........d02

r03...........d03

TABLE C:

returnID.......rentID

t01...............r01

i want to select dvd that not in Table B (rented) except it in Table C (returned) so the output should be like this:

OUTPUT:

dvdID.......dvdTitle

d01..........Avenger

could you help me?

Was it helpful?

Solution 2

Try this,

SELECT *
FROM A 
WHERE (NOT EXISTS (SELECT * FROM B WHERE B.dvdID=A.dvdID))
   OR (EXISTS (SELECT * FROM C,B WHERE C.rentID=B.rentID and B.dvdID=A.dvdID))

here is SQLFiddle

OTHER TIPS

You can use existential quantifiers in your SQL conditions, represented by the EXISTS keyword:

SELECT *
FROM TableA a
WHERE NOT EXISTS (        -- No rental record
    SELECT *
    FROM TableB b
    WHERE b.dvdID=a.dvdID -- The record is for this DVD, and...
      AND NOT EXISTS (    -- ...there is no return record
          SELECT * FROM TableC c WHERE c.rentID=b.rentID
      )
)

The query reads almost like a poorly constructed English sentence, but it explains what is going on.

From your sample data set it is clear that you need the dvds whose rent exists in TableC for this you can do so a simple INNER join ,last join from table3 will satisfy the rent exist condition for a dvd from table1

select t1.* FROM
Table1 t1
LEFT JOIN Table2 USING(dvdID)
JOIN Table3 USING(rentID)

Fiddle Demo

try this Option 1

select * from A 
where dvdID not in (Select dvdID from B where rentID not in (select rentID from C))

You should use JOINS instead of EXISTS / NOT EXISTS

SELECT 
    a.*
FROM TableA a
    LEFT join TableB b
        on b.id=a.id
    LEFT Join TableC c 
        on c.id=a.id
WHERE
    b.id is null 
    OR (b.id is not null AND c.id is not null)

Try this:

SELECT TableA.dvdID, TableA.dvdTitle 
FROM TableA
LEFT JOIN TableB ON TableA.dvdID = TableB.dvdID
LEFT JOIN TableC ON TableC.rentID = TableB.rentID
WHERE TableB.rentID IS NULL
   OR (TableB.rentID IS NOT NULL
       AND TableC.returnID IS NOT NULL)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top