MYSQL使用一个查询的行计数通过比较值来限制结果

时间:2015-02-17 20:38:03

标签: mysql

如何使用子查询将table1上返回的结果与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

输出应返回table2行1& 2;因为配额是2,所以满足第0行,并且主数据a有两行。第1行错过了配额1,因此它应该与第2行一起返回。

这是我的思路:

(mysql影响了psuedo - 代码,不用说它不起作用!) -

SELECT * FROM table2 
WHERE quota > COUNT(
    SELECT id FROM table1 
    WHERE table1.master = table2.master
)

2 个答案:

答案 0 :(得分:2)

尝试将HAVING与联接

一起使用
SELECT * FROM table2
INNER JOIN table1 USING (master)
GROUP BY master HAVING COUNT(*) < quota

答案 1 :(得分:0)

您可以INNER JOIN从table2到表一的count子查询,并返回配额&gt;的情况。计数

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