我想知道如何检查用户是否已经在数据库中。
在PHP中,我有一个带有一些UserID的数组。 即userIDs [0] = 1234; userIDs [1] = 2345;
现在我想构建一个查询,如果可能的话,只进行一次SQL调用以获得以下结果:
############################
# UserID # Exists #
############################
# 1234 # 0 #
# 2345 # 1 #
############################
是否有sql解决方案或我是否必须通过单独的呼叫检查每个ID? 谢谢你的帮助!
答案 0 :(得分:0)
根据您可以执行的列表检查现有id
select userId, userId in (2345,5678) as `exists`
from your_table
order by userId
但要检查数据库中是否有id
列表,您可以
select tmp.userId, tab.userId is not null as `exists`
from
(
select 1234 as userId
union all
select 2345
union all
select 3456
) tmp
left join db_table tab on tab.userId = tmp.userId
答案 1 :(得分:0)
X:
用PHP建立你的查询,这是一个字符串。
$idsFromFacebook = array(1234,2345,3456,4567);
//start query
$strQuery = "select tmp.userId, tab.userId is not null as `exists` from (";
$bfirstRun = true;
//Go through each element of the array and connect them with the query string
foreach( $idsFromFacebook as $userID )
{
//There is no union all before the first element and after the last
if ( !$bFirstRun )
$strQuery .= " union all ";
$strQuery .= "select ".$userID;
if ( $bFirstRun )
{
//"as userId" is only needed the first time
$strQuery .= " as userId";
$bFirstRun = False
}
}
//Finishing the query by joining the generated table with database
$strQuery .= ") tmp left join db_table tab on tab.userId = tmp.userId;";
//Call Query
$result = $dbms->query($strQuery);
//...
这就是它。因为查询是一个字符串,所以你可以像想要的那样构建它:)