Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use results from one sql query in another where statement (subquery?)

I see many similar questions but they're either so complex I can't understand them, or they don't seem to be asking the same thing.

It's simple: I have two columns: users (dmid) and downloads (dfid).

  1. Select all users who downloaded a specific file:

    SELECT DISTINCT dmid FROM downloads_downloads where dfid = "7024" 
  2. Using the users above, find all the files they all downloaded:

    SELECT dfid from downloads_downloads WHERE dmid = {user ids from #1 above} 
  3. Count and order the dfid results , so we can see how many downloads each file received:

    dfid    dl_count_field ----    -------------- 18       103 3        77 903      66 

My attempt at answering.

This seems close, but MySql bogs down and doesn't respond even after 30 seconds--I restart Apache eventually. And I do not now how to structure the count and order by without getting syntax errors because of the complex statement--and it may not even be the right statement.

SELECT dfid from downloads_downloads WHERE dmid IN (     SELECT DISTINCT dmid FROM `downloads_downloads` where dfid = "7024") 
like image 953
Josh Bond Avatar asked Dec 08 '12 16:12

Josh Bond


People also ask

How do I use results of a SQL query in another query?

Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.

Can you use subquery in a WHERE clause of the SQL query?

Subqueries in the WHERE Clause. A subquery in a WHERE clause can be used to qualify a column against a set of rows. For example, the following subquery returns the department numbers for departments on the third floor. The outer query retrieves the names of employees who work on the third floor.

Can a subquery contain another subquery?

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.


1 Answers

SELECT dfid,count(*)  from downloads_downloads  WHERE dmid IN (     SELECT dmid      FROM downloads_downloads      where dfid = "7024" ) group by dfid 

or using a self join

select t1.dfid,count(*) from downloads_downloads t1 inner join downloads_downloads t2 on t1.dmid = t2.dmid where t2.dfid = "7024" 

if this takes too long then you will probably need to post an explain plan (google it!)

like image 108
Paul Creasey Avatar answered Sep 28 '22 16:09

Paul Creasey