从查询返回的总mysql结果具有限制:FOUND_ROWS错误

时间:2012-10-16 13:05:33

标签: mysql join left-join limit

我有这个mysql查询:

SELECT Files.GUID, Files.Name, Files.Type, Files.Visibility, Files.CreationDate, Files.OwnerUser, Date, BackupsCount
FROM Files
  LEFT JOIN (
    SELECT FileGUID, Date, COUNT(*) AS BackupsCount
    FROM Versions
    GROUP BY FileGUID
  ) Versions ON Files.GUID = Versions.FileGUID
WHERE Files.ParentFolder = '96251A8B-B2A8-416B-92D7-3509E6A645C7'
ORDER BY Files.Type DESC, CreationDate ASC
LIMIT 0, 50

我想知道这个查询会返回多少记录如果LIMIT指令不存在,我用Google搜索并发现我需要添加SELECT SQL_CALC_FOUND_ROWS和{{ 1}}

我的问题是:我无法让它发挥作用:

SELECT FOUND_ROWS();

假设这是个好主意(我的意思是执行一个查询而不是两个单独的查询),如何让SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT Files.GUID, Files.Name, Files.Type, Files.Visibility, Files.CreationDate, Files.OwnerUser, Date, BackupsCount FROM Files LEFT JOIN ( SELECT FileGUID, Date, COUNT(*) AS BackupsCount FROM Versions GROUP BY FileGUID ) Versions ON Files.GUID = Versions.FileGUID WHERE Files.ParentFolder = '96251A8B-B2A8-416B-92D7-3509E6A645C7' ORDER BY Files.Type DESC, CreationDate ASC LIMIT 0, 50) -- Find total rows SELECT FOUND_ROWS() 使用此查询?

3 个答案:

答案 0 :(得分:1)

查询应该是这样的:

SELECT SQL_CALC_FOUND_ROWS Files.GUID, Files.Name, Files.Type, Files.Visibility, Files.CreationDate, Files.OwnerUser, Date, BackupsCount
FROM Files
  LEFT JOIN (
    SELECT FileGUID, Date, COUNT(*) AS BackupsCount
    FROM Versions
    GROUP BY FileGUID
  ) Versions ON Files.GUID = Versions.FileGUID
WHERE Files.ParentFolder = '96251A8B-B2A8-416B-92D7-3509E6A645C7'
ORDER BY Files.Type DESC, CreationDate ASC
LIMIT 0, 50

答案 1 :(得分:1)

这个想法是正确的,第二个查询几乎是即时的。但是你必须在SELECT之后添加关键字,不再是:

SELECT Files.GUID, Files.Name, Files.Type, ...

变为

SELECT SQL_CALC_FOUND_ROWS Files.GUID, Files.Name, Files.Type, ...

然后会填充找到的行数,您就可以恢复它了。

如果您想运行一个检索查询,但是您能够执行多个查询,那么您可以执行此操作(这是两个查询):

SELECT COUNT(*) INTO @FOUNDROWS FROM ( YOUR_QUERY_WITHOUT_SELECT ) AS orig;

并通过将@FOUNDROWS as foundrows添加到字段来更改您的检索查询:

SELECT ...YOUR FIELDS..., @FOUNDROWS AS foundrows FROM...

最后,您可以将JOIN作为包含两个查询的单个查询运行:

SELECT ALL_YOUR_FIELDS, counter.FOUND_ROW_NUMBER FROM
( YOUR_QUERY_WITH_LIMIT ) AS limited
JOIN ( SELECT COUNT(*) AS FOUND_ROW_NUMBER FROM YOUR_QUERY ) AS counter;

答案 2 :(得分:0)

A very simple example


 "SELECT SUM(final_cost) as final_cost,
SUM(call_discount) as discount_cost,
(SELECT COUNT(*) FROM call_records WHERE transaction_type ='call' AND account_id='$account_id' AND time_of_call>='$from' AND time_of_call<='$to' ) as calls,
(SELECT COUNT(*) FROM call_records WHERE transaction_type ='text' AND account_id='$account_id' AND time_of_call>='$from' AND time_of_call<='$to' ) as texts,
(SELECT COUNT(*) FROM call_records WHERE transaction_type ='appointment' AND account_id='$account_id' AND time_of_call>='$from' AND time_of_call<='$to' ) as appts
 FROM
 call_records
 WHERE account_id='$account_id'
 AND time_of_call>='$from'
 AND time_of_call<='$to' "