简体   繁体   中英

Counting only search result in SQL with COUNT function

I have a product table and now I want to count the total result when a user search for an item, and not counting the total item in product table.

Example :

Suppose I have 4 rows in product table and I make a SQL query to match product title field, description field and item number field : if the search return 2 rows, how do I count this result so I can use it for pagination purpose ?

Below is the sql query am using :

$titleSQL[]  = "if (title LIKE $key,$scoreTitleKeyword,0)";
$descSQL[]   = "if (description LIKE $key,$scoreDescriptionKeyword,0)";
$ItenNoSQL[] = "if (item_number = $nowildcardKey,$scoreItemNumberKeyword,0)";

$sql = "SELECT 
          p.product_id, 
          p.title, 
          p.price, 
          p.unit_sold, 
          p.slug, 
          p.discount, 
          p.free_shipping, 
          free_return, 
          p.profile_img, 
          p.store_name, 
          p.item_number,
          (
            (-- Title score ".implode(" + ", $titleSQL).")+
            (-- description ".implode(" + ", $descSQL).")+
            (-- item number ".implode(" + ", $ItenNoSQL).")+
            (-- category id ".implode(" + ", $catIdSQL).")
          ) as relevance
        FROM products p
        WHERE p.is_active = '1'".$sortpriceHighLow."
        HAVING relevance > 0
        ORDER BY ".$orderBy." relevance DESC
        LIMIT 10";

If a user search return 2 rows from the resulting query I want to use COUNT function so I can get 2 but I can't seen to get it work...

I tried :

$sql = "SELECT COUNT(*),
          (
            (-- Title score ".implode(" + ", $titleSQL).")+
            (-- description ".implode(" + ", $descSQL).")+
            (-- item number ".implode(" + ", $ItenNoSQL).")+
            (-- category id ".implode(" + ", $catIdSQL).")
          ) 
        FROM products p
        WHERE p.is_active > '1'";

But all query in database were selected and not according to the search result

You would seem to want:

SELECT COUNT(*),
FROM products p
WHERE p.is_active > '1' AND
      (
        (-- Title score ".implode(" + ", $titleSQL).")+
        (-- description ".implode(" + ", $descSQL).")+
        (-- item number ".implode(" + ", $ItenNoSQL).")+
        (-- category id ".implode(" + ", $catIdSQL).")
       ) > 0;

However, you may simply want SELECT SQL_CALC_FOUND_ROWS . . . SELECT SQL_CALC_FOUND_ROWS . . . and SELECT FOUND_ROWS() (see here ). This is the more typical method for doing pagination.

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