Wednesday, 11 September 2013

Check if row used by another table

Check if row used by another table

I have a table emails_accounts with a structure like this:
¨X¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨[
¨U id ¨U email ¨U description ¨U
¨d¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨g
¨U 1 ¨U test@gmail.com ¨U Lorem ¨U
¨U 2 ¨U example@example.com ¨U Ipsum ¨U
¨U 3 ¨U test@example.com ¨U Dolor ¨U
¨U 4 ¨U retail@example.com ¨U Sit Amet ¨U
¨^¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨a
And a second table email_templates with a structure similiar to this:
¨X¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨j¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨[
¨U id ¨U email_title ¨U email_from ¨U email_to ¨U
¨d¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨p¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨g
¨U 1 ¨U Test title ¨U 1 ¨U 3 ¨U
¨U 2 ¨U Second title ¨U 2 ¨U 3 ¨U
¨U 3 ¨U Some title ¨U 1 ¨U 1 ¨U
¨^¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨m¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨a
What I want to achieve is to create a SQL query which gives me ALL
accounts from the table emails_accounts but with additional information -
how much every account is used in a table email_templates (it needs to
check email_from and email_to).
I know it shouldn't be too hard, but so far I didn't manage to get the
results right. My code at the moment is:
SELECT acc.* , COUNT( temp.id )
FROM emails_accounts acc
LEFT JOIN email_templates temp ON acc.id = temp.email_from
GROUP BY acc.email
But I would like to have both email_from and email_to counted.
I tried also this:
SELECT acc . * , COUNT( temp.id ) + COUNT( temp2.id ) AS count
FROM emails_accounts acc
LEFT JOIN email_templates temp ON acc.id = temp.email_from
LEFT JOIN email_templates temp2 ON acc.id = temp2.email_to
GROUP BY acc.email
But it gives too many results.

No comments:

Post a Comment