mysql选择多行,MySQL选择与相关表中的多行匹配的行

The following tables are much larger, but have been downsized for ease of the question

Table 1 - exercise_rolladex

Exercise_ID | Exercise_Name

---------------------------

1 Pushups

2 Turkish Get Ups

3 Squats

4 Ice Skater

Table 2 - exercise_planes

Exercise_Plane_ID | Exercise_Plane

----------------------------------

1 Sagittal

2 Frontal

3 Transverse

Table 3 - exercise_has_planes

Exercise_ID | Exercise_Plane_ID

-------------------------------

1 1

2 1

2 2

2 3

3 1

4 2

4 3

My question is: How can I structure a Query where I can find the Exercise_ID of each exercise which has Exercise_Plane_ID=1 AND Exercise_Plane_ID=2. In other words, find the exercises that have both Sagittal AND Frontal planes of motion.

The Correct Query

SELECT e.Exercise_Name, p.Exercise_Plane

FROM exercise_rolladex e

INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID

INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID

WHERE p.Exercise_Plane_ID IN(2,1)

GROUP BY e.Exercise_ID

HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

UPDATE FOLLOW UP QUESTION

How then would I include an exclusion? for example, find the exercises with plane_id 2 and 3, but exclude exercises with plane_id 1 (The correct result being "Ice Skater")

I went ahead and answered my own question:

SELECT e.Exercise_Name, p.Exercise_Plane

FROM exercise_rolladex e

INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID

INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID

WHERE p.Exercise_Plane_ID IN(2,3)

AND e.Exercise_ID NOT IN

(SELECT Exercise_ID FROM exercise_has_planes WHERE Exercise_Plane_ID='1')

GROUP BY e.Exercise_ID

HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

Thanks to Mr. Brownstones answer from a different question.

SQL query to exclude items on the basis of one value

解决方案

You can do something like this,this will check the plan id with your given input ids and filter out there count in each exercise group if count returns more than one then it means exercise has planes,having clause will fulfill the scenario of having both planes in exercise

SELECT e.Exercise_Name,

p.Exercise_Plane

FROM exercise_rolladex e

INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID

INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID

WHERE p.Exercise_Plane_ID IN(2,1)

GROUP BY e.Exercise_ID

HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值