Solved

MYSQL: How to combine two queries

Posted on 2013-01-10
3
597 Views
Last Modified: 2013-01-11
Dear Experts.

I have two tables.

Table 1 has the following columns.

id
host
count

The following query sets the count field to 3 where the host is microsoft.com

UPDATE hosts SET `count` =  '3' WHERE  hosts.host = "microsoft.com";  

Open in new window


Table 2 has the following columns.

id
host
company_emails
sent

This query provides a list of hosts with the corresponding count of emails sent

SELECT `host` , COUNT( * ) AS total FROM  `company_emails` WHERE `sent` = 1 GROUP BY host ORDER BY COUNT( * ) DESC;

Open in new window


How would I combine the two queries so that hosts.count field contains the "total" value calculated in the second query?

Many thanks.
0
Comment
Question by:AdrianSmithUK
  • 2
3 Comments
 
LVL 12

Accepted Solution

by:
jessegivy earned 500 total points
Comment Utility
Maybe this?

UPDATE
hosts,
(SELECT host, COUNT( * ) as total FROM  `company_emails` WHERE `sent` = 1 GROUP BY host) as emails
SET hosts.`count` =  emails.total WHERE  hosts.host = email.host;
0
 

Author Closing Comment

by:AdrianSmithUK
Comment Utility
Almost perfect. A small typo (email.host) should read emails.host.

You're a star!

Many thanks.
Adrian
0
 

Author Comment

by:AdrianSmithUK
Comment Utility
Final solution: (in case I need to cut and paste it at some time)

UPDATE HOSTS ,
(
SELECT host, COUNT( * ) AS total
FROM  `company_emails` 
WHERE  `sent` =1
GROUP BY host
) AS emails
SET hosts.`count` = emails.total WHERE hosts.host = emails.host

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now