MySQL& php PDO如何获取:SELECT EXISTS(SELECT 1 FROM x WHERE y =:value)

时间:2012-06-04 14:40:58

标签: php mysql sql pdo

我正在使用这种语法而不是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} 

但它似乎没有回复正确的任何想法?

2 个答案:

答案 0 :(得分:5)

这里使用EXISTS似乎不对。只需执行此查询:

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

答案 1 :(得分:0)

正确使用就像正常一样,捕获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
}