我需要帮助MySQL中的以下SubQuery
SELECT ... # Main query
...
... IN # Start of subquery that expects to return an array of a.id
(SELECT a.id, a.multipler
FROM a
JOIN b ON a.id = b.id
GROUP BY(a.id)
HAVING COUNT(b.id) * a.multipler < 5)
我想要实现的是对表b(b.id)中存在的所有a.id进行分组。 我想用每个a.id的唯一mulitpler(a.multipler)计算结果和多个。
这里的问题是我希望这是一个子查询:因此我不能得到2个结果。但是,为了使用“HAVING”,我需要在结果集中包含每个变量。
我只想要/需要“a.id”而不使用“a.multipler”作为结果。有什么想法可以解决这个问题吗?
示例代码:
#table a
+------+-------------+
| a_id | a_multipler |
+------+-------------+
| 1 | 2.000 |
| 2 | 0.560 |
| 3 | 1.000 |
| 4 | 1.200 |
| 5 | 2.000 |
+----- +-------------+
#table b
+------+
| b_id |
+------+
| 1 |
| 1 |
| 1 |
| 4 |
| 4 |
| 3 |
+------+
# a.id 1: occurance in "table b": 3 x 2.000 ("a.id"==1 "a.multipler"). Fails, result >= 5
#a.id 2: Fails, no occurance of a.id in "table b".
#a.id 3: 1 x 1.000. Result < 5 OK
# and so on... "id" in "table a" (but not in "table b") is unique,
# also a "id" in "table b" have to exist in "table a".
根据上述查询(a.id)得出结果:4,3
不想要结果:
(a.id):4,3
(a.multipler):1.200,1.000
答案 0 :(得分:0)
然后,将子查询包装在另一个只选择所需列的SELECT
中:
SELECT ... # Main query
...
... IN
(SELECT pairs.id FROM # <===
(SELECT a.id, a.multipler
FROM a
JOIN b ON a.id = b.id
GROUP BY(a.id)
HAVING COUNT(b.id) * a.multipler < 5) pairs)
任何(子)查询都会产生一个可以进一步操作的临时表,在这种情况下只需选择一个列的子集即可。