56

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")
Scimonster
  • 32,893
  • 9
  • 77
  • 89
Josh Bond
  • 1,719
  • 4
  • 17
  • 26
  • 3
    You shouldn't use double quotes (`"`) for character literals, use single quotes instead. The double quotes are a MySQL thing and won't work with other DBMS (because in standard SQL double quotes are used for identifiers, not for literals). And if that dfid is a numeric value, you shouldn't be using any quotes all. Numbers don't need quotes. –  Dec 08 '12 at 17:47

1 Answers1

64
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!)

Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
  • 4
    for me solution #1 works, and its quite easily understandable , but can you please explain, me solution #2 i can under stand self join – noobie-php Jan 29 '14 at 14:17
  • @paul-creasey I know this is old, but can you explain the second code? – Rafael Oct 06 '15 at 13:15
  • Heads up: if your ultimate goal is to perform an `update`, the first approach will result in an error, which this other answer helped me resolve: https://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause – Mike B Apr 07 '21 at 01:08
  • I used both of these for my use case, dumped the first solution into the second solution's where statement. – TeflonMusk Aug 25 '21 at 21:45