在一对一关系中获得没有特定价值的所有条目SQL

发布于 2025-02-07 06:59:58 字数 559 浏览 3 评论 0原文

我有一个锻炼台和一个标签表。每个练习都可以有几个标签,所以我有一个与多个关系的第三个桌子。

我尝试实现的是获得所有没有特定标签的练习。

数据示例:

Exercise 1
Exercise 2
Exercise 3

Tag 1
Tag 2

Exercise 1 - Tag 1
Exercise 1 - Tag 2
Exercise 2 - Tag 1
Exercise 3 - Tag 2

在这种情况下,寻找没有标签1的练习,我应该只参加练习3。

我最后的尝试是:

SELECT Exercise.id FROM Exercise, Tags 
INNER JOIN TagsExercises 
ON Exercise.id=TagsExercises.idExercise AND TagsExercises.idTag=Tags.id 
WHERE Tags.id NOT in ( '3' )
GROUP BY Exercise.id;

我得到练习3和练习1,因为标签2 ... uu 不确定如何形成SQL,有什么想法吗?

I have a Exercise table, and a Tag table. Each exercise can have several tags so I have a third table for the one to many relationship.

What I try to achieve is getting all the exercises that does NOT have a specific tag.

Data example:

Exercise 1
Exercise 2
Exercise 3

Tag 1
Tag 2

Exercise 1 - Tag 1
Exercise 1 - Tag 2
Exercise 2 - Tag 1
Exercise 3 - Tag 2

In this case, looking for exercises not having tag 1, I should get Exercise 3 only.

Last attempt I have is:

SELECT Exercise.id FROM Exercise, Tags 
INNER JOIN TagsExercises 
ON Exercise.id=TagsExercises.idExercise AND TagsExercises.idTag=Tags.id 
WHERE Tags.id NOT in ( '3' )
GROUP BY Exercise.id;

And I get Exercise 3 AND Exercise 1 because of the entry with tag 2... u.u
Not sure how to form the SQL, any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾铮苏瑾 2025-02-14 06:59:58

您需要表的所有id s 练习除了具有标签'1'的:

SELECT id FROM Exercise
EXCEPT
SELECT idExercise FROM TagsExercises WHERE idTag = '1'; 

仅当您想要时使用operator in 包含多个标签。

或:

SELECT id 
FROM Exercise
WHERE id NOT IN (SELECT idExercise FROM TagsExercises WHERE idTag = '1');

You want all the ids of the table Exercise except the ones that have a tag '1':

SELECT id FROM Exercise
EXCEPT
SELECT idExercise FROM TagsExercises WHERE idTag = '1'; 

Use the operator IN only if you want to include more than one tags.

Or:

SELECT id 
FROM Exercise
WHERE id NOT IN (SELECT idExercise FROM TagsExercises WHERE idTag = '1');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文