【问题标题】:SQL query where 2 or more records exist in second table第二个表中存在 2 个或更多记录的 SQL 查询
【发布时间】:2015-05-17 20:16:52
【问题描述】:

我有 3 个表,想要选择表 1 中的所有记录,其中表 2 中的所有记录都连接表 3 并被选中。

我知道有一个子查询的方法,但不知道它是什么。

一个简单的谁在上什么课的问题。

我使用 sqlite3 作为数据库。

Students table t1(id int,名称文本)

id      name
------- ---------
1       Smith
2       Jones
3       Wilson
--------------------------------------------------

Classestable t2(类 int,学生 int)

class   student
------- ---------
1       1
1       2
1       3
2       1
2       2
3       1
3       3
4       2
4       3

Selected table t3 (t3class int, t3checked boolean)

t3Class t3Checked
------- ---------
1       false
2       false
3       true
4       true

谁在上课

Class   Name
-----   --------
1,2 = Smith, Jones
1,3 = Smith, Wilson
1,4 = Jones, Wilson
1,2,4   = Jones
1,2,3,4 = 

【问题讨论】:

  • 我不太确定是这样。我只寻找上过课的学生。因此,如果表 3 全部为 false 且 class1&2 为 true,则答案将是 Smith 和 Jones。
  • 忽略上面的评论,我无法编辑或删除它。我不太确定是不是这样。我正在寻找一个查询,它只会返回已参加所有标记为 true 的课程的学生。因此,如果所选表只有 1 和 2 为真,则将返回 Smith & Jones。如果 Selected 表的 1 和 3 为真,则返回 Smith & Wilson。如果所选表的 1 & 2 & 4 为 true,则仅返回 Jones 如果所选表的 1 & 2 & 3 & 4 为 true,则不会返回任何记录。

标签: sql sqlite subquery


【解决方案1】:

我不能 100% 确定这在 SQLite 中是否有效,因为它不支持 group_concat() 中的 order by。但是,你可以试试这个:

select classes, group_concat(student)
from (select student, group_concat(class) as classes
      from classes c
      group by student
     ) sc
 group by classes;

在 MySQL 中,正确的版本应该是:

select classes, group_concat(student order by student)
from (select student, group_concat(class order by class) as classes
      from classes c
      group by student
     ) sc
group by classes;

需要排序以确保同一班级的两个学生按正确的顺序排列。

【讨论】:

  • 这不是我想要的。我正在寻找一个查询,该查询仅返回已参加所有标记为 true 的课程的学生。在选定的表中,如果 1 和 2 为真,则返回 Smith & Jones。如果 1 & 3 为真,则返回 Smith & Wilson。如果 1 & 2 & 4 为真,则仅返回 Jones 如果 1 & 2 & 3 & 4 为真,则不会返回任何记录
  • @user2797484 。 . .您的结果包括第 1 类和第 2 类,即使它们未被选中。我很困惑。
  • 我描述不正确。基本上,最终用户正在更新“选定”表。当我在上面说 1&2 时,我表示他们选择了 1&2 并且所有其他值都是错误的。所以上面描述的不同场景是通过改变 Selected 表来创建的。我基本上是在寻找一个只有在所有选定的记录都存在时才会找到行的查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2013-12-13
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多