无论如何,他们是否要使用 group by 将连接添加到 returns 特定列的最新行的查询中

Is their anyway to add a join to a query that returns the latest rows of a specific column using group by

 "SELECT * FROM report
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";

上面的代码为我提供了每个组织每个 request_id 的最新行,这正是我想要的,但我需要在 table 中使用 FK 以获得更多详细信息。 我想加入一个组织并请求 table 上述查询,以便我可以使用 FK 在我的报告页面上显示某些内容。

我以不同的方式尝试了下面的代码,但我总是得到这个错误。

警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result,第 503 行 C:\xampp\htdocs\mou1\organizationDetails.php 中给出的布尔值

"SELECT * FROM report
      JOIN request ON
      report.id = report.request_id
      JOIN organization ON
      organization.id = report.org_id
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";

Code Snippet

据推测,您的查询失败是因为 idWHERE 子句中不明确。您需要限定此列名称:

SELECT * 
FROM report
JOIN request ON request.id = report.request_id
JOIN organization ON organization.id = report.org_id
WHERE report.id IN (
    SELECT MAX(id)
    FROM report
    where org_id = '$id'
    GROUP BY request_id
) 

我修复了 request 的连接条件中的拼写错误(您有 ON report.id = report.request_id)。

我会向前迈出一步,建议重写此查询并使用相关子查询。 MySQL 往往无法优化带有子查询的 IN 过滤器,而如果有适当的索引可用,相关子查询通常表现得非常好:

select *   -- you should enumerate the columns here
from report rep
inner join request req      on req.id = rep.request_id
inner join organization org on org.id = rep.org_id
where rep.id = (
    select max(rep1.id)
    from report rep1
    where rep1.org_id = ? and rep1.request_id = rep.request_id
)

请注意,我使用 table 别名来使查询更具可读性并缩短它。您还应该使用参数化查询,而不是在查询字符串中连接变量(? 代表此处的查询参数)。

为了提高此查询的性能,您需要在 report(org_id, requsst_id, id) 上建立索引。