php—他们的方法是向查询添加一个连接,该查询使用GROUPBY返回特定列的最新行

hi3rlvi2  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(216)
"SELECT * FROM report
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";

上面的代码为我提供了每个组织每个请求的最新一行id,这正是我想要的,但是我需要使用表中的fk来获得更多细节。我想将一个organization&request表加入到上面的查询中,这样我就可以使用fk在我的报表页上显示某些内容。
我尝试了下面的代码在不同的方式,但我总是得到这个错误。
警告:mysqli\u fetch\u assoc()期望参数1是mysqli\u result,bool在c:\xampp\htdocs\mou1\organizationdetails.php的第503行中给出

"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
             ) ";

代码段

8ljdwjyq

8ljdwjyq1#

您的查询可能会失败,因为 id 是模棱两可的 WHERE 条款。您需要限定此列名:

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 带有子查询的flter,而如果有合适的索引可用,则相关的子查询通常表现得非常好:

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
)

请注意,我使用了表别名来提高查询的可读性并缩短它。您还应该使用参数化查询,而不是在查询字符串中串联变量 ? 此处表示查询参数)。
为了提高此查询的性能,您需要在 report(org_id, requsst_id, id) .

相关问题