简体   繁体   中英

How to count the expected number of rows

When I have a mysql query like this:

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

How can I know how many results there are without LIMIT 0, 30 .

Pseudo query:

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`

This gives me a list like this:

  • 3
  • 1
  • 1
  • 1

etc.

But I am expecting something like this:

  • 137

My current solution In my opinion this is a bad programming practice:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM