Web Wiz - Green Windows Web Hosting

  New Posts New Posts RSS Feed - Tricky Query problem - Many to Many structure.
  FAQ FAQ  Forum Search   Events   Register Register  Login Login

Tricky Query problem - Many to Many structure.

 Post Reply Post Reply
Author
ctytrungloi View Drop Down
Newbie
Newbie


Joined: 09 December 2008
Status: Offline
Points: 5
Post Options Post Options   Thanks (0) Thanks(0)   Quote ctytrungloi Quote  Post ReplyReply Direct Link To This Post Topic: Tricky Query problem - Many to Many structure.
    Posted: 24 February 2009 at 3:41am
My contact  trà
I'm having trouble creating a query for this problem... I have 3 tables:

tblUser
(int primary key) id
(varchar) name

tblGroup
(int primary key) id
(varchar) name

tblUserGroup
(int) group_id
(int) user_id
unique index on group_id, user_id

Users can belong to more than one group so tblUserGroup is a many to many relationship.

If I'm given a selection of user ids that are from tblUser e.g. (45,23,854,2,96) how do I select the group from tblGroup which is made up of the most number of users from the selection, but also only contains users which are in the selection? There are several hundred thousand groups and the query needs to be fast... i've come up with one way but it's pretty slow.

SELECT tblGroup.id, tblGroup.name
FROM tblGroup
INNER JOIN tblUserGroup
ON tblUserGroup.group_id = tblGroup.id AND tblUserGroup.user_id IN (45,23,854,2,96)
LEFT JOIN tblUserGroup AS tblUserGroup2
ON tblUserGroup.group_id = tblGroup.id AND tblUserGroup2.user_id NOT IN (45,23,854,2,96)
WHERE tblUserGroup2.group_id IS NULL
GROUP BY tblGroup.id

Is there a better way to do this? I'm willing to reorganize the tables entirely if many to many is not the best way to go.
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down

Forum Software by Web Wiz Forums® version 12.08
Copyright ©2001-2026 Web Wiz Ltd.


Become a Fan on Facebook Follow us on X Connect with us on LinkedIn Web Wiz Blogs
About Web Wiz | Contact Web Wiz | Terms & Conditions | Cookies | Privacy Notice

Web Wiz is the trading name of Web Wiz Ltd. Company registration No. 05977755. Registered in England and Wales.
Registered office: Web Wiz Ltd, Unit 18, The Glenmore Centre, Fancy Road, Poole, Dorset, BH12 4FB, UK.

Prices exclude VAT at 20% unless otherwise stated. VAT No. GB988999105 - $, € prices shown as a guideline only.

Copyright ©2001-2026 Web Wiz Ltd. All rights reserved.