Help with query with joins -
02-14-2007
, 05:48 PM
Thanks to all that are taking a look at this.
I'm trying to create a query that will get some information from a
main table as well as some aggregated from other tables. For example,
let's say I have three tables with some fields:
User: username, firstname, lastname
Purchase: username, date, amount, items
View: username, date, pageUrl
I want to create a query that will get the user's info (username and
first and last name) as well as the total purchase amounts and the
total page views. I have this as a query:
SELECT u.username, u.firstname, u.lastname, sum(p.amount) AS
totalAmount, count(v.pageUrl) AS countPages
FROM (User u LEFT JOIN Purchase p ON u.username=p.username) LEFT JOIN
View v ON u.username=v.username
GROUP BY u.username, u.firstname, u.lastname;
This query works, but takes forever (with ~2000 users, ~2 purchases/
user, ~10 views/user = ~20 minutes). Clearly this is not ideal.
Does someone have any idea on how I could create a better query to
handle this?
Thanks in advance, Andy |