[英]How do I get results of a MySQL JOIN where records meet a value criteria in joined table?
This may be simple but I can't figure it out...这可能很简单,但我无法弄清楚......
I have two tables:我有两个表:
tbl_results: tbl_results:
runID | balance |
1 | 3432
2 | 5348
3 | 384
tbl_phases: tbl_phases:
runID_fk | pc |
1 | 34
1 | 2
1 | 18
2 | 15
2 | 18
2 | 20
3 | -20
3 | 10
3 | 60
I want to get a recordset of: runID, balance, min(pc), max(pc) only where pc>10 and pc<50 for each runID as a group, excluding runIDs where any associated pc value is outside of value range.我想获得一个记录集: runID、balance、min(pc)、max(pc) ,其中每个 runID 的pc>10 和 pc<50作为一个组,不包括任何关联的 pc 值超出值范围的 runID。
I would want the following results from what's described above:我希望从上面描述的结果中得到以下结果:
runID | balance | min_pc | max_pc
2 | 5348 | 15 | 20
... because runID=1&3 have pc values that fall outside the numeric range for pc noted above. ...因为 runID=1&3 的 pc 值超出了上述 pc 的数字范围。
Thanks in advance!提前致谢!
You may apply filters based on your requirements in your having clause.您可以根据您在您的拥有条款中的要求应用过滤器。 You may try the following.您可以尝试以下方法。
Query #1查询#1
SELECT
r.runID,
MAX(r.balance) as balance,
MIN(p.pc) as min_pc,
MAX(p.pc) as max_pc
FROM
tbl_results r
INNER JOIN
tbl_phases p ON p.runID_fk = r.runID
GROUP BY
r.runID
HAVING
MIN(p.pc)>10 AND MAX(p.pc) < 50;
runID运行ID | balance平衡 | min_pc min_pc | max_pc最大PC |
---|---|---|---|
2 2 | 5348 5348 | 15 15 | 20 20 |
Query #2查询#2
SELECT
r.runID,
MAX(r.balance) as balance,
MIN(p.pc) as min_pc,
MAX(p.pc) as max_pc
FROM
tbl_results r
INNER JOIN
tbl_phases p ON p.runID_fk = r.runID
GROUP BY
r.runID
HAVING
COUNT(CASE WHEN p.pc <= 10 or p.pc >= 50 THEN 1 END) =0;
runID运行ID | balance平衡 | min_pc min_pc | max_pc最大PC |
---|---|---|---|
2 2 | 5348 5348 | 15 15 | 20 20 |
View working demo on DB Fiddle查看 DB Fiddle 上的工作演示
Updated with comments from Rahul Biswas更新了 Rahul Biswas 的评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.