【问题标题】:mysql finding not exist records in mutiple tablesmysql发现多个表中不存在记录
【发布时间】:2018-08-23 06:50:09
【问题描述】:
    CREATE TABLE `Students` (
  `id` int(11) NOT NULL,
  `name` varchar(500) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `Students` (`id`, `name`) VALUES
(1, 'Student 1'), 
(2, 'Student 2'),
(3, 'Student 3');



CREATE TABLE `lessons` (
  `id` int(11) NOT NULL,
  `name` varchar(500) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `lessons` (`id`, `name`) VALUES
(1, 'Lesson 1'),
(2, 'Lesson 2'),
(3, 'Lesson 3');



CREATE TABLE `completed` (
  `student` int(11) NOT NULL,
  `lesson` varchar(500) NOT NULL,
  `completed` int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



INSERT INTO `completed` (`student`, `lesson`, `completed`) VALUES
(1, 2, 1),
(3, 3, 1),
(2, 1, 1);

我们正在将完成课程的学生添加到“已完成”表中。我们需要让 5 个学生的课程 ID 不存在于“已完成”表中。

示例输出是;

1, 1
1, 3
2, 2
2, 3
3, 1
3, 2

谢谢

【问题讨论】:

  • 在我看来像 LEFT JOIN 的工作。
  • 到目前为止你尝试了什么???

标签: mysql join exists


【解决方案1】:

以下应该显示所有没有完成课程的学生,这就是我认为您所要求的:

SELECT Students.id, Students.name FROM Students LEFT JOIN completed
ON Students.id = completed.student WHERE completed.student IS NULL;

【讨论】:

  • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“WHERE completed.student IS NULL LIMIT 0, 30”附近使用正确的语法
  • 修复了连接条件
【解决方案2】:

您可以使用NOT EXISTS

SELECT s.Id, s.Name
FROM Students s
WHERE NOT EXISTS (
    SELECT 1
    FROM Completed
    WHERE s.Id = student
)

【讨论】:

  • 对不起,我不明白你的代码;来自学生?选择 1?
  • @ÖnderErol 它会给你想要的结果吗?
  • @ÖnderErol 它会抓取Student 中不存在于Completed 中的所有学生。
  • 抱歉,结果为空白。
  • @ÖnderErol 所有学生都存在于Completed 中吗?学生是否完成有什么区别? completed 列(1 或 0)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
相关资源
最近更新 更多