1

请考虑以下项目表:

Project:
  table: project
  manyToMany:
    themes:
      targetEntity: Theme
      inversedBy: projects
      joinTable:
        name: project_theme
        joinColumns:
          project_id:
            referencedColumnName: id
        inverseJoinColumns:
          theme_id:
            referencedColumnName: id
    platforms:
      targetEntity: Platform
      joinTable:
        name: project_platform
        joinColumns:
          project_id:
            referencedColumnName: id
        inverseJoinColumns:
          platform_id:
            referencedColumnName: id
  manyToOne:
    client:
      targetEntity: Client

如您所见,一个项目具有三个关系;主题通过 project_theme 连接表,平台通过 project_platform 表,客户端通过 client_id 列。

我正在尝试生成一个查询,该查询将找到所有相关项目——具有相同主题、平台或客户的项目——并按“分数”对它们进行排序。

例如:

项目一:
  主题:18、19
  平台:1、4
  客户:22

查找与项目 A.. 相关的项目

项目 D:
  主题:18、19
  平台:1、4
  客户:22
得分:5
项目 G:
  主题:18、21
  平台:3、4
  客户:22
得分:3
项目B:
  主题:8、21
  平台:2、4
  客户:1
得分:1

我真的很感谢一些为此编写 MySQL 查询的助手。我一直在为以下问题苦苦挣扎-但我可能还很遥远:

SELECT 
    `project`.*,
    GROUP_CONCAT(`project_theme`.`theme_id`) as themes,
    GROUP_CONCAT(`project_platform`.`platform_id`) as platforms,
    `project`.`client_id` as client
FROM `project`
LEFT JOIN `project_theme` ON `project`.`id` = `project_theme`.`project_id`
LEFT JOIN `project_platform` ON `project`.`id` = `project_platform`.`project_id`
GROUP BY `project`.`id`

非常感谢
皮特的任何帮助

4

2 回答 2

0

我在平板电脑上,所以我会很简短。将它们视为三个单独的查询并将它们合并。当我有键盘时,我会带着 sql 回来。

于 2012-11-22T14:01:25.437 回答
0

感谢您在阅读高级查询后提示马林。对mysql中最相关的字段进行排名,并进行一些实验,我想我可能已经破解了它......

SELECT 
    p.*,
    (
        IFNULL(themes.matches, 0) + IFNULL(platforms.matches, 0) + IFNULL(clients.matches, 0)
    ) as score
FROM `project` p
LEFT JOIN (
    SELECT t2.project_id, COUNT(*) as matches FROM `project_theme` t1, `project_theme` t2
    WHERE 
      t1.theme_id = t2.theme_id AND t1.project_id = 1
      GROUP BY t2.project_id
) themes ON p.id = themes.project_id
LEFT JOIN (
    SELECT f2.project_id, COUNT(*) as matches FROM `project_platform` f1, `project_platform` f2
    WHERE 
      f1.platform_id = f2.platform_id AND f1.project_id = 1
      GROUP BY f2.project_id
) platforms ON p.id = platforms.project_id
LEFT JOIN (
    SELECT p2.id, COUNT(*) as matches FROM `project` p1, `project` p2
    WHERE 
      p1.client_id = p2.client_id AND p1.id = 1
      GROUP BY p2.id
) clients ON p.id = clients.id
GROUP BY p.`id`
HAVING score > 0
ORDER BY score DESC;
于 2012-11-22T14:15:31.140 回答