Question

I'm learning SQL using a textbook and a database downloaded from my PHP/SQL driven CMS website (because, like someone suggested, I have an understanding of what various query results should look like).

I'm more familiar with MS Access where I would create queries, save them and then run queries against them. This allowed me to break larger data analysis tasks down in to smaller, easier to comprehend pieces.

Anyway, the goal of the SQL session is to find the ten people in my email database who have received the most emails. The following query provides each instance of an email being sent to an email address:

SELECT alert.alert_recipient,alert_sent.id
FROM alert
INNER JOIN alert_sent
ON alert_sent.alert_id=alert.id

Now, I would like to query the above query. If the results of the above query were a table I would want something along the lines of (I"m a newb and the syntax may be wrong):

SELECT COUNT(DISTINCT alert_recipient, ID) FROM myqueryabove
ORDER id DESC
LIMIT 10;

I asked this question in a previous post and was given an answer. The answer gave me one query to cover it all and produce the results in one query.

What I'm asking this time around concerns the method. As opposed to one big query, can I save the first query as "query_1_all_emails" and then query it like a table (like I do in Access)? If I can, is this good or common practice?

Was it helpful?

Solution 2

Ways to "query a query" include:

Create a view. Use a derived table, aka a subquery with an alias. Here is how that one works:

select count(distinct alert_recipient, id) 
from (SELECT alert.alert_recipient,alert_sent.id
FROM alert
INNER JOIN alert_sent
ON alert_sent.alert_id=alert.id ) temp
order id desc
limit 10

Or, you can create a text file with this sql.

SELECT alert.alert_recipient,alert_sent.id
FROM alert
INNER JOIN alert_sent
ON alert_sent.alert_id=alert.id
order id desc
limit 10

and copy and paste it into your query tool whenever you want to run it. Or, some query tools will allow you to save query files so you can run them whenever you want.

OTHER TIPS

You can use a view or save the result of the first query in a temporary table and then query that view / table. However, the best method to retrieve the information you are after seems to be the use of one query only, on the line of:

select
    count(*),
    alert_recipient
from
    alert
group by alert_recipient
order by 1 desc
limit 10;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top