简体   繁体   中英

How to intersect two Selects with Joins? SQL

I have a table with Artists and another with Prints. I want to get everything from the table Artist and just the print_id from the table Prints. Imagine if I have 3 Artists A, B and C. Imagine if artist A and B participated in print 1 and also 2. Artist C participated on print 2 and 3. What I want is the info about artist A and B because they participated on print 1 but also what other prints they participated (in this case, print 2).

Table Artist : Artist A - Brazil. Artist B - USA. Artist C - Belgium.

Table Print: 1 - Wave. 2 - Map. 3 - Night.

Result Expected: Artist A - Brazil - 1. Artist A - Brazil - 2. Artist B - USA - 1. Artist B - USA - 2.

I'm trying like this but I'm getting some errors...

SELECT 
    * 
FROM   
    (SELECT DISTINCT 
         artist.*
        ,print.print_id 
     FROM   
         artist 
         JOIN print ON artist.artist_id = print.artist_id 
     WHERE  
         print.print_id = 1 
     INTERSECT
     SELECT DISTINCT 
         artist.*
        ,print.print_id 
     FROM   
         artist JOIN print ON artist.artist_id = print.artist_id
    )

You can try using join for the table (select) you have

SELECT * FROM (
   SELECT DISTINCT
       Artist.*,
       Print.print_id 
   FROM Artist 
   JOIN Print
   ON Artist.artist_id = Print.artist_id 
   WHERE Print.print_id=1
   ) as T1 
JOIN
   (
   SELECT DISTINCT
       Artist.*,
       Print.print_id 
   FROM Artist 
   JOIN Print ON Artist.artist_id = Print.artist_id
   ) as T2 
   ON T1.artist_id = T2.artist_id

essentially the selects are at tables while a INTERSESCT corresponds to a INNER JOIN with the bond of union keys of the two tables/select

The only sensible way I can understand the query is to assume that a WHERE clause is missing from the second subquery.

If you want to use join to check if an artist has two prints, then:

SELECT a.*
FROM Artist a JOIN
     Print p1
     ON a.artist_id =  p1.artist_id AND p1.print_id = 1 JOIN
     Print p2
     ON a.artist_id =  p2.artist_id AND p2.print_id = 2;

I see no reason to select print_id in the SELECT , because the artist has both.

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