tags:

views:

48

answers:

1

I have two tables one is table Profile and other is table Profile_location (stores the relation of a profile and a location). Problem:

A user can have multiple profiles, each profile has different locations. I want to find crossover of locations between each profile of a given user. In other words, evaluate all the profiles of a given user and find the locations which are not unique.

A quick help would be really appreciated.

User ID and Location ID comes from table users and location.

Table Profile:          Profile_ID, Profile_Name, User_ID, Other details ...
Table Profile_Location: ProLoc_ID, Location_ID(FK), Profile_ID(FK)
Table Users:            User_ID, Username, etc.
Table Location:         Location_ID, Location_Name, etc.
A: 
SELECT
  l.Location_ID,
  l.Location_Name
FROM
  Location l
WHERE
  EXISTS (
      SELECT 1 
        FROM Profile p
  INNER JOIN Profile_Location pl ON pl.Profile_ID = p.Profile_ID
             AND pl.Location_ID = l.Location_ID
       WHERE p.User_ID = <USER_ID_PARAM>
    GROUP BY pl.ProLoc_ID
      HAVING COUNT(*) > 1
  )
Tomalak
unknown column l since Location l doesn't exist in that context of subquery. I am running it as mysql query. Not sure if it's ok for SQL Server
Martin Chen
It *should* exist. MySQL can do correlated sub-queries and it is defined on the outer query, after all.
Tomalak
Sorry to bother you again Tom. Here is what I have got:[SQL] select tbl_region.id, tbl_region.`name`from tbl_regionwhere EXISTS( select 1 from tbl_profile INNER JOIN tbl_profile_location ON tbl_profile_location.profile_id = tbl_profile.id AND tbl_profile_location.region_id = tbl_region.id where tbl_profile.user_id = 109 GROUP BY tbl_profile_location.id having COUNT(*) > 1)[Err] 1054 - Unknown column 'tbl_region.id' in 'on clause'
Martin Chen
@Shahan: Okay. [The MySQL docs state that this construct should be possible](http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html). **a)** Can you get the inner query to run by itself? (just substitute the `tbl_region.id` with an actual region ID) **b)** Try to move the `AND tbl_profile_location.region_id = tbl_region.id` to the WHERE clause and see if that makes a difference.
Tomalak
solution (b) worked. thanks for your valuable input Tom.
Martin Chen
@Shahan: You're welcome. Good to hear that it worked, finally.
Tomalak