You could use a subquery:
select t1.*,
(select coalesce(sum(number_of_tickets), 0) from t2 where t2.table_1_id = t1.id) as number_of_tickets
from t1
With an index on t2(table_1_id, number_of_tickets)
, this should be an efficient option.
As for your original code (that was added as an edit to the question). The intent is OK, the problem is with the GROUP BY
clause, that is not consistent with the SELECT
clause. In MySQL, you could write this as:
SELECT p.id , p.title, SUM(r.number_of_tickets) AS reserved_tickets
FROM plays p
INNER JOIN reservations r ON p.id = r.play_id
GROUP BY p.id
ORDER BY reserved_tickets
All non-aggregated columns in the SELECT
clause come from table plays
, and we group by plays.id
, wich presumably is the primary key of that table.
Note that I modified the query to use table aliases: this is good practice, that makes the queries easier to write and read. Also note that column aliases are allowed in the ORDER BY
clause.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…