【问题标题】:MySQL find crossovers in a table for different profiles for a same userMySQL 在表中为同一用户的不同配置文件查找交叉点
【发布时间】:2010-10-17 09:20:36
【问题描述】:

我有两张表,一张是Profile,另一张是Profile_location(存储配置文件和位置的关系)。问题:

一个用户可以有多个个人资料,每个个人资料都有不同的位置。我想找到给定用户的每个配置文件之间的位置交叉。换句话说,评估给定用户的所有个人资料并找出不唯一的位置。

我们将不胜感激。

用户 ID 和位置 ID 来自表用户和位置。

表配置文件:Profile_ID、Profile_Name、User_ID、其他详细信息... 表 Profile_Location:ProLoc_ID、Location_ID(FK)、Profile_ID(FK) 表用户:User_ID、用户名等。 表位置:Location_ID、Location_Name 等。

【问题讨论】:

    标签: sql mysql


    【解决方案1】:
    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
      )
    

    【讨论】:

    • 未知列 l 因为位置 l 在子查询的上下文中不存在。我将它作为 mysql 查询运行。不确定 SQL Server 是否可以
    • 应该存在。 MySQL 可以进行相关的子查询,毕竟它是在外部查询中定义的。
    • 很抱歉再次打扰你,汤姆。这是我得到的: [SQL] select tbl_region.id, tbl_region.name from tbl_region where 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 具有 COUNT(*) > 1 ) [Err] 1054 - 'on 子句'中的未知列 'tbl_region.id'
    • @Shahan:好的。 The MySQL docs state that this construct should be possiblea) 你能让内部查询自行运行吗? (只需将 tbl_region.id 替换为实际的区域 ID)b) 尝试将 AND tbl_profile_location.region_id = tbl_region.id 移动到 WHERE 子句中,看看是否会有所不同。
    • @Shahan:不客气。很高兴听到它终于奏效了。
    猜你喜欢
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多