MySQL query calculated column
I have these queries:
SELECT a.Id, a.Name, (SELECT COUNT(Id) FROM b WHERE b.IdTableA = a.Id) AS Num
FROM a
ORDER BY a.Name
table b has a FK on table a (IdTableA) In this case, is it efficient? Is there any other way to do this?
The other question is:
SELECT client.Id, client.Name
,(SELECT SUM(projects) FROM projects WHERE IdClient = client.Id) AS pr开发者_如何学Cojects
FROM client
What about this one?
Sometimes we need to use more than one calculated column (SELECT SUM), even 10 or 15.
We very are worried about performance since the table projects could have more than 500K records.
I've read that storing those SUMS in a table and update that table when the data changes could be better for performance. But this goes against normalization...
Please help me with both queries...
Thanks
SELECT a.Id, a.Name, (SELECT COUNT(Id) FROM b WHERE b.IdTableA = a.Id) AS Num
FROM a
ORDER BY a.Name
can possible be rewritten as
SELECT a.Id, a.Name, COUNT(b.Id) AS Num
FROM a JOIN b ON b.IdTableA = a.Id
GROUP BY a.Id, a.Name
ORDER BY a.Name
which carries less risk of being wrongly executed by MySQL.
Storing sums of data for easy retrieval is acceptable when you have a lot more reads than writes (or when writes are allowed to be slow, but reads have to be fast). Usually you use a data-warehouse for this though: the warehouse stores the aggregate data, and your OLTP database stores the individual rows.
精彩评论