0

我有这个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 指令不存在,这个查询将返回多少条记录,我用谷歌搜索发现我需要添加SELECT SQL_CALC_FOUND_ROWSSELECT 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()

假设这是个好主意(我的意思是做一个查询而不是两个单独的查询),我怎样才能让FOUND_ROWS()这个查询工作?

4

3 回答 3

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
于 2012-10-16T13:37:11.977 回答
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;
于 2012-10-16T13:41:16.073 回答
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' "
于 2014-04-06T16:01:52.943 回答