Author Topic: SELECT, GROUP, ORDER BY, JOIN all in one query  (Read 321 times)

0 Members and 1 Guest are viewing this topic.

Offline dreamwestTopic starter

  • Devotee
  • Gender: Male
    • View Profile
SELECT, GROUP, ORDER BY, JOIN all in one query
« on: June 30, 2009, 06:42:08 AM »
Im trying to make a query to tell how many videos each user has uploaded, but the there are two tables and i need to sort by amount of videos descending

Heres what ive done
Code: [Select]
$query = "SELECT videos.*, signups.* ".
 "FROM videos, signups ".
"WHERE videos.user_id = signups.user_id limit 5 ";

$result = mysql_query($query) or die(mysql_error());


// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['username']. " has ". $row['   ']." videos";
echo "<br />";
}

Heres my table structure

Table1:
signups (tabe name)

user_id  |  username

Table 2:
videos (Table name)

id |  user_id 


I proberly need a count or group in here but im uncertain
My code doesn't have bugs...Just unexpected benefits

Offline dzelenika

  • Enthusiast
    • View Profile
Re: SELECT, GROUP, ORDER BY, JOIN all in one query
« Reply #1 on: June 30, 2009, 07:10:56 AM »
Code: [Select]
SELECT sugnups.username, Count(*)
FROM videos, signups
WHERE videos.user_id = signups.user_id
GROUP BY sugnups.username
ORDER BY 2 DESC
« Last Edit: June 30, 2009, 07:11:31 AM by dzelenika »

Offline dreamwestTopic starter

  • Devotee
  • Gender: Male
    • View Profile
Re: SELECT, GROUP, ORDER BY, JOIN all in one query
« Reply #2 on: June 30, 2009, 06:18:19 PM »
Thanks. The query works,  but im still having trouble with the while loop

Code: [Select]
while($row = mysql_fetch_array($result)){
echo $row['username']." has ".$row['COUNT(id)']." videos";
echo "<br />";
}

The username is grouped and echos but doesnt have any video count
« Last Edit: June 30, 2009, 06:19:06 PM by dreamwest »
My code doesn't have bugs...Just unexpected benefits

Offline dzelenika

  • Enthusiast
    • View Profile
Re: SELECT, GROUP, ORDER BY, JOIN all in one query
« Reply #3 on: July 01, 2009, 05:54:00 AM »
Thanks. The query works,  but im still having trouble with the while loop

Code: [Select]
while($row = mysql_fetch_array($result)){
echo $row['username']." has ".$row['COUNT(id)']." videos";
echo "<br />";
}

The username is grouped and echos but doesnt have any video count

Put $row[1]

Instead of

$row['COUNT(id)']

Offline fenway

  • MySQL Si-Fu / PHP Resident Alien
  • Global Moderator
  • 'Insane!'
  • *
  • Gender: Male
    • View Profile
Re: SELECT, GROUP, ORDER BY, JOIN all in one query
« Reply #4 on: July 01, 2009, 09:12:14 PM »
Oh, please don't do that... don't rely on array offsets.

Use a column alias and refer to it that way.
:anim_rules: Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.

PHP Freaks Forums

« on: »

Tired of these ads? Purchase a supporter subscription to get rid of them.