如何抓取两个表之间的相关行?
How to grab related rows between two tables?
我的表:
Table 1
excercises
| primaryMuscleGroup | motionName |
| ------------------ | -------------- ------|
| Chest | Dips |
| Chest | Chest Press |
| Chest | Push Up |
| Chest | Flye |
| Legs | Squat |
| Legs | Lunge |
| Back | Deadlift |
Table 2
fitnessRecords
| name | motionName |
| ------------------ | -------------- ------|
| John Smith | Dips |
| Sally | Squat |
| Wallace | Lunge |
| Christoph | Deadlift |
查询应该 return 一个人未完成的肌肉群的所有练习。例如,如果我们 运行 查询客户“John Smith”,我们应该 return:
| primaryMuscleGroup | motionName |
| Legs | Squat |
| Legs | Lunge |
| Back | Deadlift |
如果我们 运行 查询客户“Sally”,我们应该 return:
| primaryMuscleGroup | motionName |
| ------------------ | -------------- ------|
| Chest | Dips |
| Chest | Chest Press |
| Chest | Push Up |
| Chest | Flye |
| Back | Deadlift |
SELECT *
FROM excercises t1
WHERE NOT EXISTS ( SELECT NULL
FROM fitnessRecords t2
JOIN excercises t3 USING (motionName)
WHERE t2.name = 'given name'
AND t1.primaryMuscleGroup = t3.primaryMuscleGroup )
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=eb216b7579d5fcd0c0ab628717f3d676
您可以使用外连接或 not exists
,看看以下是否是您需要的:
select *
from exercises e
where not exists (
select * from exercises x
where exists (
select * from fitnessRecords fr
where fr.name = 'john smith' and fr.motionName = x.motionName
) and x.primaryMuscleGroup = e.primaryMuscleGroup
)
我的表:
Table 1
excercises
| primaryMuscleGroup | motionName |
| ------------------ | -------------- ------|
| Chest | Dips |
| Chest | Chest Press |
| Chest | Push Up |
| Chest | Flye |
| Legs | Squat |
| Legs | Lunge |
| Back | Deadlift |
Table 2
fitnessRecords
| name | motionName |
| ------------------ | -------------- ------|
| John Smith | Dips |
| Sally | Squat |
| Wallace | Lunge |
| Christoph | Deadlift |
查询应该 return 一个人未完成的肌肉群的所有练习。例如,如果我们 运行 查询客户“John Smith”,我们应该 return:
| primaryMuscleGroup | motionName |
| Legs | Squat |
| Legs | Lunge |
| Back | Deadlift |
如果我们 运行 查询客户“Sally”,我们应该 return:
| primaryMuscleGroup | motionName |
| ------------------ | -------------- ------|
| Chest | Dips |
| Chest | Chest Press |
| Chest | Push Up |
| Chest | Flye |
| Back | Deadlift |
SELECT *
FROM excercises t1
WHERE NOT EXISTS ( SELECT NULL
FROM fitnessRecords t2
JOIN excercises t3 USING (motionName)
WHERE t2.name = 'given name'
AND t1.primaryMuscleGroup = t3.primaryMuscleGroup )
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=eb216b7579d5fcd0c0ab628717f3d676
您可以使用外连接或 not exists
,看看以下是否是您需要的:
select *
from exercises e
where not exists (
select * from exercises x
where exists (
select * from fitnessRecords fr
where fr.name = 'john smith' and fr.motionName = x.motionName
) and x.primaryMuscleGroup = e.primaryMuscleGroup
)