Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2010
    Posts
    8

    Unanswered: can I do this with a single query and no PHP?

    Hello

    Let's say I retrieve the most viewed productIDs with this query:

    Code:
    SELECT productid, COUNT(productid) AS views FROM products WHERE products.merchantcategory = 'categoryname') ORDER BY views DESC LIMIT 3
    then I'll check with php the number of returned rows, if this number is 0 I'll run the query again but replacing this category with its parent:

    Code:
    SELECT productid, COUNT(productid) AS views FROM products WHERE products.merchantcategory = 'parentcategoryname' ORDER BY views DESC LIMIT 3
    I suppose this can be done in a smarter way within the query, but I don't understand why

    I tried searching for IF condition samples but honestly I can't get them to work ( MySQL :: MySQL 5.0 Reference Manual :: 11.4 Control Flow Functions )

    basically I'd like to run a query like this:
    Code:
    IF (query1 returns 0 rows) { execute euery2 and return its results} else { return query1 results }
    any suggestions?
    Last edited by uhm; 09-06-10 at 14:27.

  2. #2
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    Hi,

    you will need to look at either stored procedures or functions in MySQL. This will more or less help you out. If the results of the productid has any results for the cat input into the stored procedure then we accept this. If on the other hand there are no results we use the parent category passed into the stored procedure as the second parameter.

    Code:
    DELIMITER //
    CREATE PROCEDURE query (cat IN VARCHAR, parentcat IN VARCHAR)
    BEGIN
      DECLARE count int;
    
      SELECT COUNT(productid) INTO count
      FROM products
      WHERE merchantcategory = cat;
    
      IF count > 0 THEN
         SELECT productid, COUNT(productid) AS views
         FROM products
         WHERE merchantcategory = cat
         ORDER BY views DESC LIMIT 3;
      ELSE
         SELECT productid, COUNT(productid) AS views
         FROM products
         WHERE merchantcategory = parentcat
         ORDER BY views DESC LIMIT 3;
      END IF;
    
    END//
    DELIMETER ;
    To call this from within your PHP code you need to execute the following (not sure of the exact syntax):

    Code:
    mysql_query(db, "call query('categoryname','parentcategoryname')");
    Ronan Cashell
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

  3. #3
    Join Date
    Mar 2010
    Posts
    8
    sorry for my late response, thank you for your help Ronan

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •