I have the following MySQL tables, where B_ID is a foreign key pointing to the ID column of Table_B:
---------- -----------
|Table_A | |Table_B |
---------- -----------
|B_ID int| |ID int |
---------- |VALUE int|
-----------
I want to compute the sum of the VALUE column in Table_B considering only IDs that appear as foreign keys in Table_A. Also, I want to add each row in Table_B at most once.
So, if the tables were filled with the following data:
------ ------------
|B_ID| |ID | VALUE|
------ ------------
|1 | |1 | 50 |
|2 | |2 | 100 |
|2 | |3 | 200 |
------ ------------
the sum would be 150 (computed as 50+100).
The query I am using now is:
SELECT SUM(b.VALUE)
FROM Table_B b
WHERE b.id IN (SELECT DISTINCT B_ID FROM Table_A)
However, I would like to avoid having a subquery if at all possible. Any ideas on how to do this without subqueries?
Note: This query is itself a subquery in a larger query, so it can only select one column.
This does not eliminate subqueries, but would be more efficient if you have few records in a
and lots in b
:
SELECT SUM(value)
FROM (
SELECT DISTINCT b_id
FROM a
) a
JOIN b
ON b.id = a.b_id
Create an index on a.b_id
for this to work fast.
If there are few records in b
and lots of them in a
, your original query will be faster. The suggestion of the index still applies.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.