search

Home  >  Q&A  >  body text

How to get related rows between two tables

My form:

表格1
练习

| primaryMuscleGroup | motionName           |
| ------------------ | -------------- ------|
| 胸部               | 双杠臂屈伸           |
| 胸部               | 卧推                 |
| 胸部               | 俯卧撑               |
| 胸部               | 飞鸟                 |
| 腿部               | 深蹲                 |
| 腿部               | 弓步                 |
| 背部               | 硬拉                 |

表格2
健身记录

| name               | motionName           |
| ------------------ | -------------- ------|
| 约翰·史密斯         | 双杠臂屈伸           |
| 莎莉               | 深蹲                 |
| 华莱士             | 弓步                 |
| 克里斯托夫         | 硬拉                 |

The query should return all exercises for muscle groups that a person has not done. For example, if we run the query for the customer "John Smith" we should return:

| primaryMuscleGroup | motionName           |
| 腿部               | 深蹲                 |
| 腿部               | 弓步                 |
| 背部               | 硬拉                 |

If we run the query for customer "Sally" we should return:

| primaryMuscleGroup | motionName           |
| ------------------ | -------------- ------|
| 胸部               | 双杠臂屈伸           |
| 胸部               | 卧推                 |
| 胸部               | 俯卧撑               |
| 胸部               | 飞鸟                 |
| 背部               | 硬拉                 |

P粉976737101P粉976737101442 days ago609

reply all(2)I'll reply

  • P粉642919823

    P粉6429198232023-09-15 19:56:41

    You can use outer joins or use not exists to see if the following query meets your needs:

    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
    )

    reply
    0
  • P粉388945432

    P粉3889454322023-09-15 12:46:32

    SELECT *
    FROM excercises t1
    WHERE NOT EXISTS ( SELECT NULL 
                       FROM fitnessRecords t2
                       JOIN excercises t3 USING (motionName)
                       WHERE t2.name = '给定的名字'
                         AND t1.primaryMuscleGroup = t3.primaryMuscleGroup )

    https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=eb216b7579d5fcd0c0ab628717f3d676

    reply
    0
  • Cancelreply