0

我在处理这个查询时遇到了问题。我想从表中获取SELECT一个项目,并从projects表中获取与其关联的所有文件projects。这是我的查询:

SELECT
    `projects`.`id` AS `project_id`,
    `projects`.`password` AS `project_password`,
    `projects`.`title` AS `project_title`,
    `projects`.`description` AS `project_description`,
    `projects`.`active` AS `project_active`,
    `files`.`file` AS `file_file`,
    `files`.`title` AS `file_title`,
    `files`.`category` AS `file_category`
FROM `projects`
LEFT JOIN `files` ON
    `projects`.`id` = "test_project3" AND
    `files`.`project_id` = "test_project3"
;

project_id我期望结果是一个包含、project_passwordproject_titleproject_descriptionproject_activefile_filefile_title和列的集合file_category(前两个字段是返回的每一行的相同数据,其余字段因文件而异)。

这不仅仅是检索项目信息和文件test_project3,这显然是返回projects表中的每个项目。

有什么建议吗?

谢谢!

4

2 回答 2

2

解决此问题的一种方法是将projects表上的谓词移动到WHERE子句,并引用连接列而不是 ON 子句中的常量。

像这样的东西:

  FROM `projects`
  LEFT
  JOIN `files`
    ON files.project_id = projects.id
 WHERE projects.id = 'test_project3'

(这是规范模式,如果您从项目中返回不止一行,您会希望使用该模式。)

于 2013-08-12T23:32:18.540 回答
0

只需使用 ainner join而不是 a left join

SELECT
    `projects`.`id` AS `project_id`,
    `projects`.`password` AS `project_password`,
    `projects`.`title` AS `project_title`,
    `projects`.`description` AS `project_description`,
    `projects`.`active` AS `project_active`,
    `files`.`file` AS `file_file`,
    `files`.`title` AS `file_title`,
    `files`.`category` AS `file_category`
FROM `projects`
INNER JOIN `files` ON
    `projects`.`id` = "test_project3" AND
    `files`.`project_id` = "test_project3"
;

保留表中的left join所有行projects,无论表中是否存在匹配项files。您想将其join用作过滤器,这就是 an 的inner join作用。

于 2013-08-12T23:25:36.903 回答