【问题标题】:MySQL & php PDO how to fetch: SELECT EXISTS (SELECT 1 FROM x WHERE y = :value)MySQL & php PDO 如何获取:SELECT EXISTS (SELECT 1 FROM x WHERE y = :value)
【发布时间】:2012-06-04 14:40:57
【问题描述】:

我使用这种语法而不是 count (*),因为它应该更快,但我不知道如何获取结果输出

$alreadyMember = $dataBase->prepare('SELECT EXISTS ( SELECT 1 
FROM TheCommunityReachLinkingTable 
WHERE communityKey = :communityKey 
AND userID = :userID)');
$alreadyMember->bindParam(':communityKey', $_POST['communityKey'], PDO::PARAM_STR);
$alreadyMember->bindParam(':userID', $_POST['userID'], PDO::PARAM_INT);
$alreadyMember->execute();

if($alreadyMember->fetch()) {do code here} 

但它似乎没有返回正确的东西,你知道吗?

【问题讨论】:

    标签: php mysql sql pdo


    【解决方案1】:

    EXISTS 的使用在这里似乎是错误的。只需执行此查询:

    SELECT 1 
    FROM TheCommunityReachLinkingTable 
    WHERE communityKey = :communityKey 
    AND userID = :userID
    

    【讨论】:

    • 我应该在最后设置 LIMIT 1 吗?
    • @NicolasManzini 仅当您知道对于任何 communityKeyuserID 组合都会返回多条记录的情况。
    【解决方案2】:

    正确的用法和平常一样,捕获fetch()的返回值

    $row = $alreadyMember->fetch();
    print_r($row); // you may have numeric or string indices depending on the FETCH_MODE you set, pick one, consider a column alias and associative
    
    
    //or the easy way
    $alreadyMember->execute();
    if ($alreadyMember-fetchColumn()) {
        //column 0 contained a truthy value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2012-08-18
      相关资源
      最近更新 更多