i have 3 tables with one to many relation {Downloads , TagNames, File_Tag}
the download table Like
| ID | File | _modifieddate |
| ------------ | ------------ | ------------ |
| 1 | FILE1.ZIP | 2/1/2023 |
| 2 | FILE2.ZIP | 3/1/2023 |
| 3 | FILE3.ZIP | 4/1/2023 |
| 4 | FILE4.ZIP | 5/1/2023 |
the TagNames table Like
ID | TagName |
---|---|
1 | system |
2 | pics |
3 | framework |
4 | compressed |
5 | info |
the File_Tag table Like
ID | FileID | TagID |
---|---|---|
1 | 1 | 1 |
2 | 1 | 3 |
3 | 1 | 4 |
4 | 2 | 4 |
5 | 2 | 2 |
6 | 3 | 1 |
7 | 3 | 4 |
8 | 4 | 5 |
9 | 4 | 4 |
what i want all downloads table records that dont have 'pics' or 'info' tag related to it
i tried
select * from (
SELECT Downloads._modifieddate, Downloads.File, Downloads.ID, ROW_NUMBER() over ( ORDER BY Downloads._modifieddate DESC ) AS aa FROM
TagNames INNER JOIN File_Tag ON TagNames.ID = File_Tag.TagID INNER JOIN Downloads ON File_Tag.FileID = Downloads.ID WHERE (TagNames.TagName <> 'pics' ) and (TagNames.TagName <> 'info' )) as product
the row_number for paging purpose but it return file2.zip because it has another row with compressed tag and it give me duplicates for every tag related to the file
what i expect
| ID | File | _modifieddate |
| ------------ | ------------ | ------------ |
| 1 | FILE1.ZIP | 2/1/2023 |
| 3 | FILE3.ZIP | 4/1/2023 |
3条答案
按热度按时间wj8zmpe11#
You need an anti-join, which in SQL is normally done using a
NOT EXISTS
Make sure you have the join condition inside the subquery, or you will get incorrect results.
If you want
Downloads
which do not have both tags, but don't mind if they only have one, then use relational division. There are a number of ways to do this, here is a simple one:wz1wpwve2#
May be something like this
7fyelxc53#
What you want is something like: