[英]MYSQL Use Row Count From One Query To Limit Results in A Second By Comparing Values
How do you compare the returned results on table1 with the quota on table2 using a subquery. 如何使用子查询将table1上的返回结果与table2上的配额进行比较。 The output should be each row that doesn't meet the quota from table2.
输出应该是不符合table2配额的每一行。
table1
--------------------------
id | master | info | here
--------------------------
0 | a | 1234 | abcd
1 | b | 2345 | bcde
2 | a | 3456 | cdef
3 | c | 4567 | defg
4 | b | 5678 | efgh
5 | b | 6789 | fghi
table2
--------------------------
id | master | quota | info
--------------------------
0 | a | 2 | abcd
1 | b | 4 | bcde
2 | c | 5 | cdef
The output should return table2 rows 1 & 2; 输出应返回table2第1和2行; row 0 is satisfied because the quota is 2, and there are two rows with master a.
由于配额为2,所以满足第0行,并且有两行包含主行a。 Row 1 just missed the quota by 1, therefore it is supposed to be returned along with row 2.
第1行刚错过了配额1,因此应该与第2行一起返回。
Here is my train of thought: 这是我的思路:
(mysql influenced psuedo - code, needless to say it doesn't work!) - (mysql影响了psuedo-代码,不用说它不起作用!)-
SELECT * FROM table2
WHERE quota > COUNT(
SELECT id FROM table1
WHERE table1.master = table2.master
)
Try using HAVING
with a join 尝试对
HAVING
使用HAVING
SELECT * FROM table2
INNER JOIN table1 USING (master)
GROUP BY master HAVING COUNT(*) < quota
You could INNER JOIN from table2 to a count subquery of table one and return the cases where quota > count 您可以将INNER JOIN从table2到表1的count子查询,并返回quota> count的情况
SELECT
t2.id,
t2.master,
c.master_count,
t2.quota,
t2.info
FROM table2 AS t2
INNER JOIN (
SELECT master, COUNT(id) AS master_count
FROM table1
GROUP BY master
) AS c
ON t2.master = c.master
WHERE
c.master_count >= t2.quota
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.