SQL Recipes
A FREE cookbook for SQL queries and examples
FAQ Search Today's Posts Mark Forums Read

SQL - Repository This forum is for you to save your favorite SQL queries in a safe place so you will always know where to find them

Go Back   SQL Recipes a FREE cookbook of SQL queries and examples > SQL queries and examples > SQL - Repository

Reply
 
LinkBack Thread Tools Search this Thread
  #1 (permalink)  
Old 05-26-2009, 04:56 AM
adallas adallas is offline
Junior Member
 
Join Date: May 2009
Posts: 1
adallas is on a distinguished road
Default Most references

I came to SQL Recipes looking for this answer; didn't find it here, but I thought I'd come back to leave the answer I eventually figured out.

Records in TableB refer to specific records in TableA, many to one. You want to know the TableA ids that have the most references in TableB to create a top 10 list.

TableA - id is primary key
TableB - fk is foreign key to TableA; not unique

Code:
SELECT `fk` FROM `TableB` 
    GROUP BY `fk` 
    ORDER BY COUNT(`fk`) DESC 
    LIMIT 10;
This will produce a list of 10 TableA.id's, ordered by the number of times the id appears in TableB.fk. I don't know if it works in all dialects, but it works for me in MySQL 5.1.

Hope it helps.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

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

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



All times are GMT. The time now is 09:45 AM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.0.0
Copyright (c) 2006-2008 SQL Recipes

1 2 3 4 5 6 7 8