简体   繁体   中英

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

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)

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.

If you have your schemas for the tables, that would help.

That said, I believe what you want to look at is the JOIN keyword. (inner/outer/left/etc). That's exactly what JOIN is meant to do (ie your title).

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