How to check whether SELECT EXISTS returns a value or not?

后端 未结 7 1451
后悔当初
后悔当初 2021-01-03 19:38

I am trying to quickly determine if a user_ID is the owner of a \'goal\'. I believe my SQL query is good, but I\'m trying to find a nice way of checking the result!

相关标签:
7条回答
  • 2021-01-03 19:53

    Don't bother with EXISTS. The in-line exists will always give one row containing "true" or "false".

    You're looking for either "zero rows" or "at least one row" so change the query to something like this and then check how many rows are returned

    SELECT 1 FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id' LIMIT 1
    
    0 讨论(0)
  • 2021-01-03 19:55

    Counting how many rows match the criteria should be easier:

    $sql = SELECT COUNT(*) FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id'
    $query = mysql_query($sql);
    $result = mysql_fetch_row($query);
    
    return $result[0] >= 1;
    
    0 讨论(0)
  • 2021-01-03 19:56

    what about this:

    $query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
    
    return  mysql_query($query) ? false : true;
    
    0 讨论(0)
  • 2021-01-03 20:06

    This way is probably faster.

    $query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
    
    if(mysql_num_rows(mysqli_query($query)) < 1) {
       // Nothing found!
    }
    
    0 讨论(0)
  • 2021-01-03 20:08

    SELECT EXISTS always returns a row! The following code uses the fastest MySql query(according to this answer: https://stackoverflow.com/a/10688065/3710053) and gives in PHP the correct result:

    $link = mysqli_connect($DB_SERV, $DB_USER, $DB_PASS, $DB_NAME);
    $query = "SELECT EXISTS (SELECT * FROM goals 
                          WHERE goal_ID='$obj_id' 
                            AND user_ID='$user_id' 
                          LIMIT 1) 
          as `row_exists`";
    
    if(mysqli_fetch_assoc(mysqli_query($link,$query))['row_exists'] ===0) {
       // Nothing found!
    }
    
    0 讨论(0)
  • 2021-01-03 20:08
    mysql_result(mysql_query("SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')"),0);
    
    0 讨论(0)
提交回复
热议问题