如何在MySQL中使用WHERE条件从两个不同的表中选择数据

时间:2019-04-13 08:48:48

标签: mysql sql

我有两个表,分别是“ 学生”和“ 用户”。我想从“ Student”表中选择与用户表的“ Student_ID”不匹配的first_name和Last_name。

SELECT student.student_id, 
       student.first_name, 
       student.last_name 
FROM   student, 
       USER 
WHERE  student.student_id != USER.student_id 

2 个答案:

答案 0 :(得分:2)

NOT IN版本相同,但性能要好一些。据此:https://www.eversql.com/sql-syntax-check-validator/

SELECT
  student.student_id,
  student.first_name,
  student.last_name
FROM
  student
WHERE
  NOT EXISTS (
    SELECT
      student_id
    from
      user
    where
      user.student_id = student.student_id
  )

答案 1 :(得分:1)

尝试使用此查询:

SELECT firstname,lastname 
FROM Student 
WHERE ID NOT IN(SELECT Student_ID from User);