Search code examples
sqliteinner-join

Get all table values if match in 2 other tables exists


I have a table "channel".

channelId
a
b
c
d

a table "video"

videoId | channelId
1       | a
2       | b
3       | c
4       | e

a table "comment"

commentID | videoID | videoID_channelID
xx        | 1       | a
yy        | 2       | b
zz        | 5       | e
tt        | 6       | f

Keys are:

  • channel.channelId = video.channelId = comment.videoID_channelID
  • video.videoId = comment.videoID

I need:

  • all channels with at least 1 video and 1 comment
  • all videos with at least 1 channel and 1 comment
  • all comments with a video and a channel

So I want to do 3 SQL statements, one for each table that references the other 2.

I tried it with a double inner-join (https://www.sqlitetutorial.net/sqlite-inner-join/) but it seems to return all combinations that fit rather than:

channelId
a
b

videoId | channelId
1       | a
2       | b

commentID | videoID | videoID_channelID
xx        | 1       | a
yy        | 2       | b

My code so far to get all channels with at least 1 video and 1 comment:

SELECT
        channel.channelId
FROM
    channel
    INNER JOIN video ON video.channelId = channel.channelId
    INNER JOIN comment ON comment.videoID_channelID = video.channelId

Solution

  • You can get all the results that you want with the same query that joins all 3 tables, but for each case select different columns:

    SELECT c.channelId
    FROM channel c
    INNER JOIN video v ON v.channelId = c.channelId
    INNER JOIN comment cm ON cm.videoID_channelID = v.channelId;
    
    SELECT v.videoID, c.channelId
    FROM channel c
    INNER JOIN video v ON v.channelId = c.channelId
    INNER JOIN comment cm ON cm.videoID_channelID = v.channelId;
    
    SELECT cm.commentID, v.videoID, c.channelId
    FROM channel c
    INNER JOIN video v ON v.channelId = c.channelId
    INNER JOIN comment cm ON cm.videoID_channelID = v.channelId;
    

    You may have to add DISTINCT after each SELECT if you get duplicates in your actual data.
    See the demo.
    Results:

    | channelId |
    | --------- |
    | a         |
    | b         |
    
    
    | videoID | channelId |
    | ------- | --------- |
    | 1       | a         |
    | 2       | b         |
    
    
    | commentID | videoID | channelId |
    | --------- | ------- | --------- |
    | xx        | 1       | a         |
    | yy        | 2       | b         |