我需要在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使用唯一的乘法器(a.multipler)进行乘法运算。
这里的问题是,我希望这是一个子查询:因此我不能有2个结果。不过,为了使用"HAVING“,我需要在结果集中包含每个变量。
我只想要/需要没有"a.multipler“的"a.id”作为结果。有什么办法来解决这个问题吗?
示例代码:
#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
发布于 2012-11-09 04:37:49
然后,将您的子查询包装在另一个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)任何(子)查询都会产生一个临时表,在本例中,只需选择其中列的一个子集,就可以进一步操作该临时表。
https://stackoverflow.com/questions/13278849
复制相似问题