php 匹配多行,PHP-选择与相关表中的多行匹配的行

这篇博客探讨了如何使用SQL查询从数据库中找出同时包含矢状面和额叶面运动的锻炼。通过内连接和子查询,作者提供了一个解决方案,并进一步扩展了查询以排除具有特定平面ID的运动。示例查询展示了如何从多个表格中筛选出符合条件的运动。
摘要由CSDN通过智能技术生成

下表较大,但为方便起见已将其缩小

表1 -exercise_rolladex

Exercise_ID | Exercise_Name

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

1 Pushups

2 Turkish Get Ups

3 Squats

4 Ice Skater

表2-Exercise_planes

Exercise_Plane_ID | Exercise_Plane

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

1 Sagittal

2 Frontal

3 Transverse

表3-Exercise_has_planes

Exercise_ID | Exercise_Plane_ID

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

1 1

2 1

2 2

2 3

3 1

4 2

4 3

我的问题是:如何构造查询,在其中可以找到每个具有Exercise_Plane_ID = 1和Exercise_Plane_ID = 2的运动的Exercise_ID.换句话说,找到既具有矢状运动又具有额叶运动的运动.

正确的查询

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

更新跟进问题

那我怎么包括一个排除项呢?例如,找到使用plane_id 2和3的练习,但排除使用plane_id 1的练习(正确的结果是“ Ice Skater”)

我继续回答自己的问题:

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

解决方法:

您可以执行以下操作,这将使用给定的输入ID检查计划ID,并过滤掉每个练习组中的计数(如果count返回一个以上),则表示练习中有飞机,having子句将满足同时拥有两个飞机在运动中

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

标签:inner-join,mysql,php

来源: https://codeday.me/bug/20191121/2054286.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值