Get all table values if match in 2 other tables exists

喜你入骨 提交于 2020-01-25 09:15:09

问题


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

回答1:


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         |


来源:https://stackoverflow.com/questions/59774266/get-all-table-values-if-match-in-2-other-tables-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!