簡體   English   中英

如何抓取兩個表之間的相關行?

[英]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             |

查詢應該為一個人返回他們沒有完成的肌肉群的所有練習。 例如,如果我們為客戶“John Smith”運行查詢,我們應該返回:

| primaryMuscleGroup | motionName           |
| Legs               | Squat                |
| Legs               | Lunge                |
| Back               | Deadlift             |

如果我們為客戶“Sally”運行查詢,我們應該返回:

| 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

您可以使用 outer join 或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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM