I need help with the following SubQuery in MySQL
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)
What I want to achive is to group all a.id that exist in table b (b.id).
I want to count the results and mulitple with an unique mulitpler (a.multipler) for each a.id.
The problem here is that I want this to be a subquery: thus I cannot have 2 results. Though, in order to use “HAVING” I need to have each variable in the result set.
I only want/need “a.id” without “a.multipler” as the result. Any ideas to solve this?
Example code:
#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".
Wanted result given the above query (a.id): 4,3
NOT wanted result:
(a.id): 4,3
(a.multipler): 1.200, 1.000
Then, wrap your subquery in another
SELECTthat selects just the column you need:Any (sub)query results in a temporary table that can be further manipulated, in this case simply by selecting a subset of it columns.