Second SELECT query if first SELECT returns 0 rows

前端 未结 5 1436
萌比男神i
萌比男神i 2020-12-01 16:31

I am trying to speed up a PHP script and I am currently pushing some PHP logic in the Mysql domain of the thing. Is there a way to make a different select query if the first

相关标签:
5条回答
  • 2020-12-01 16:52
    SELECT * 
    FROM proxies 
    WHERE A=(CASE WHEN
                 (SELECT COUNT(*) FROM proxies WHERE A='B') > 0 THEN'B' 
                  ELSE 'C' END)
    

    UPDATE

    SELECT * 
    FROM proxies 
    WHERE (
        CASE WHEN (SELECT COUNT(*) FROM proxies WHERE A='B' LIMIT 1) > 0 THEN
                (A='B')
             WHEN (SELECT COUNT(*) FROM proxies WHERE A='C' LIMIT 1) > 0 THEN
                (A='C')
             WHEN (SELECT COUNT(*) FROM proxies WHERE A='D' LIMIT 1) > 0 THEN
                (A='D')
             ELSE 1=2 END)
    
    0 讨论(0)
  • 2020-12-01 16:53

    I think this more or less covers what you're trying to do. If you need the count of rows returned just get the value from mysqli->num_rows

    $db = new mySQLi(etc);
    
    //run your first query
    
    $query = "SELECT * FROM proxies WHERE A='B'";
    $result = $db->query($query);
    
    //check for rows returned
    
    if($result->num_rows > 0){
    
        //if there are rows get them
    
        while($row = $result->fetch_assoc()){
    
            //deal with the results
    
        }
    
    } else {
    
        //otherwise run your other query and get those results
    
        $query = "SELECT * FROM proxies WHERE A='C'";
        $result = $db->query($query);
        while($row = $result->fetch_assoc()){
    
            //deal with the results
    
        }
    }
    
    0 讨论(0)
  • 2020-12-01 16:53

    Another way:

    SELECT A INTO @v FROM proxies ORDER BY A LIMIT 1;
    SELECT * FROM proxies WHERE A=@v
    
    0 讨论(0)
  • 2020-12-01 17:09

    One option would be to use UNION ALL with EXISTS:

    SELECT * 
    FROM proxies 
    WHERE A='B'
    UNION ALL
    SELECT * 
    FROM proxies 
    WHERE A='C' AND NOT EXISTS (
        SELECT 1
        FROM proxies 
        WHERE A='B'
    )
    
    • SQL Fiddle Demo

    This will return rows from the proxies table where A='B' if they exist. However, if they don't exist, it will look for those rows with A='C'.

    0 讨论(0)
  • 2020-12-01 17:12

    In a general case where you have multiple values for A (lets say, 'B', 'C', 'D', 'E', etc.) and you want to retrieve only the rows that belong to the lowest value that exists, then you would use the following query. This will work also for the particular case you exposed.

    SELECT p1.*
    FROM proxies p1
    LEFT JOIN proxies p2
        ON p1.A > p2.A
    WHERE p2.A IS NULL
    

    Fiddle

    0 讨论(0)
提交回复
热议问题