如何计算预期的行数

时间:2014-03-10 15:36:36

标签: php mysql

当我有这样的mysql查询时:

SELECT 
    i.`pk_faq_item`, 
    i.`title`, 
    i.`question`, 
    i.`featured`, 
    i.`published`, 
    DATE_FORMAT(i.`datecreated`, '%d-%m-%Y %H:%i') as `datecreated`, 
    DATE_FORMAT(i.`datechanged`, '%d-%m-%Y %H:%i') as `datechanged`, 
    i.`creator`, 
    i.`userchanged`, 
    if(ISNULL(s.`vote`), 0,SUM(s.`vote`)) as `votes`, 
    if(ISNULL(s.`vote`), 0,COUNT(*)) as `seen`
FROM `faq_item` i
LEFT JOIN `faq_item_stats` s ON i.`pk_faq_item` = s.`fk_faq_item`
GROUP BY i.`pk_faq_item`
LIMIT 0, 30

如何在没有LIMIT 0, 30的情况下知道有多少结果。

伪查询:

SELECT COUNT( * ) 
FROM  `faq_item` i
LEFT JOIN  `faq_item_stats` s ON i.`pk_faq_item` = s.`fk_faq_item` 
GROUP BY i.`pk_faq_item`

这给了我一个这样的列表:

  • 3
  • 1
  • 1
  • 1

但我期待这样的事情:

  • 137

我目前的解决方案 在我看来,这是一个糟糕的编程习惯:

$query = $db->query("
     SELECT 
        i.`pk_faq_item`, 
        i.`title`, 
        i.`question`, 
        i.`featured`, 
        i.`published`, 
        DATE_FORMAT(i.`datecreated`, '%d-%m-%Y %H:%i') as `datecreated`, 
        DATE_FORMAT(i.`datechanged`, '%d-%m-%Y %H:%i') as `datechanged`, 
        i.`creator`, 
        i.`userchanged`, 
        if(ISNULL(s.`vote`), 0,SUM(s.`vote`)) as `votes`, 
        if(ISNULL(s.`vote`), 0,COUNT(*)) as `seen`
    FROM `faq_item` i
    LEFT JOIN `faq_item_stats` s ON i.`pk_faq_item` = s.`fk_faq_item`
    GROUP BY i.`pk_faq_item`
");

$totalRows = $query->rowCount();

$query = $db->query("
     SELECT 
        i.`pk_faq_item`, 
        i.`title`, 
        i.`question`, 
        i.`featured`, 
        i.`published`, 
        DATE_FORMAT(i.`datecreated`, '%d-%m-%Y %H:%i') as `datecreated`, 
        DATE_FORMAT(i.`datechanged`, '%d-%m-%Y %H:%i') as `datechanged`, 
        i.`creator`, 
        i.`userchanged`, 
        if(ISNULL(s.`vote`), 0,SUM(s.`vote`)) as `votes`, 
        if(ISNULL(s.`vote`), 0,COUNT(*)) as `seen`
    FROM `faq_item` i
    LEFT JOIN `faq_item_stats` s ON i.`pk_faq_item` = s.`fk_faq_item`
    GROUP BY i.`pk_faq_item`
    LIMIT 0, 30
");

1 个答案:

答案 0 :(得分:3)

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT SQL_CALC_FOUND_ROWS * FROM ints LIMIT 3;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
+---+

SELECT FOUND_ROWS();
+--------------+
| FOUND_ROWS() |
+--------------+
|           10 |
+--------------+