If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > How to query this?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-11-12, 08:22
jack007 jack007 is offline
Registered User
 
Join Date: Feb 2012
Posts: 1
How to query this?

Hi all,

I am new here and want to know how to query the following:

I have tables users and a table news

the fields in news are text, photo, video

in text, photo and video columns the user_id from the users goes.

Now I want to display the list of all users order by the number of records they have in news table.

LIKE:
SELECT COUNT(*) as num FROM news WHERE text='$id_user' OR photo='$id_user' OR video='$id_user'

this query will give us which user has maximum number of records in news tables based on text, photo and video.

Actually I want to display the users in descending order based on the sum of of text OR photo OR video column.

Any help for this will highly be appreciated.

regards
Reply With Quote
  #2 (permalink)  
Old 02-11-12, 09:36
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Code:
SELECT users.user_id
     , SUM(CASE WHEN news.user_id = `text` THEN 1 END +
           CASE WHEN news.user_id = photo  THEN 1 END +
           CASE WHEN news.user_id = video  THEN 1 END ) AS num 
  FROM users
LEFT OUTER
  JOIN news 
    ON news.user_id IN ( `text` , photo , video )
   AND news.user_id = users.userid
GROUP
    BY users.user_id
ORDER
    BY num DESC
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On