Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all in table where a column in table 1 exists in another table and a second column equals a variable in second table

Tags:

sql

select

I know the title is confusing but its the best I could explain it. Basically im developing a cinema listings website for a company which owns two cinemas. So I have a database which has the two tables "Films" and "Listings" with data for both cinemas in them.

I'm trying to select all films and their data for one cinema if the films name shows up in the listings (since the two cinemas share all films but in the table but the may not have the same films showing)

Here is what i have come up with but I run into a problem as when the "SELECT DISTINCT" returns more than one result it obviously cant be matched with the FilmName on tbl Films. How can i check this value for all FilmNames on tblFilms?

SELECT * 
FROM tblFilms
WHERE FilmName = (SELECT DISTINCT FilmName FROM tblListings WHERE Cimema = 1)
like image 326
James Avatar asked Dec 05 '22 12:12

James


1 Answers

use IN if the subquery return multiple values,

SELECT * 
FROM tblFILMS 
WHERE FilmName IN (SELECT DISTINCT FilmName FROM tblListings WHERE Cimema = 1)

Another way to solve thius is by using JOIN (which I recommend)

SELECT  DISTINCT    a.* 
FROM    tblFILMS a
        INNER JOIN tblListings b
            ON a.FilmName = b.FilmName AND
                b.Cimema = 1

for faster query execution, add an INDEX on FilmName on both tables.

like image 184
John Woo Avatar answered Dec 08 '22 04:12

John Woo