[英]SQLite query select all records that does not exist in another table
I am having some problem when trying to perform a SQLite query to get the records which does not exist from another table. 尝试执行SQLite查询以获取另一个表中不存在的记录时遇到问题。 Basically I have two database tables:
基本上我有两个数据库表:
My exercise table stored all the exercises available whereas the bookedExercise table store the exercises booked by each users. 我的练习表存储了所有可用的练习,而bookedExercise表存储了每个用户预订的练习。 What I am trying to do is, for example if the exercise does exist in the bookedExercise, it should be filtered out.
我想做的是,例如,如果该练习确实存在于bookedExercise中,则应将其过滤掉。
Here is the SQLite query which I used: 这是我使用的SQLite查询:
SELECT exercise.exerciseID, exercise.exerciseType, exercise.amout FROM exercise LEFT JOIN bookedExercise WHERE exercise.exerciseID = bookedExercise.exerciseID AND bookedExercise.exerciseID IS NULL
However, it returned me empty records. 但是,它返回了我空的记录。 Any ideas?
有任何想法吗?
Thanks in advance. 提前致谢。
如果您不使用联接很好,则可以使用
SELECT * FROM exercise WHERE exerciseID not in (SELECT exerciseID FROM bookedExercise)
Your SQL looked okay... I think the problem might be you have a datatype mismatch. 您的SQL看起来还不错...我认为问题可能是您的数据类型不匹配。 You have exercise ID as an integer in one table and text in another.
您在一个表中将运动ID作为整数,在另一个表中将其作为文本。
Also, if you have huge data volumes, you may want to consider an anti-join: 另外,如果您的数据量很大,则可能需要考虑使用反联接:
select
e.*
from
exercise e
where not exists (
select 1
from bookedExercise be
where
e.excerciseId = be.exerciseID
)
-- edit -- -编辑-
On second glance, your SQL was not okay. 乍一看,您的SQL不好。 You had your join condition in the where clause.
您在where子句中有加入条件。 This little change would fix your existing SQL:
这个小的更改将修复您现有的SQL:
SELECT exercise.excerciseId , exercise.exerciseType , exercise.amout
FROM exercise LEFT JOIN bookedExercise on
exercise.excerciseId = bookedExercise.exerciseID
WHERE bookedExercise.exerciseID IS NULL
When you are using LEFT JOIN, you must put the join condition into the ON clause: 使用LEFT JOIN时,必须将连接条件放入ON子句中:
SELECT exercise.exerciseID,
exercise.exerciseType,
exercise.amout
FROM exercise /* !! */
LEFT JOIN bookedExercise ON exercise.exerciseID = bookedExercise.exerciseID
WHERE bookedExercise.exerciseID IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.