MySQL: 如何检查是否列出了用户
MySQL: How can I check whether Users are listed or not
我想知道如何检查用户是否已经在数据库中。
在 PHP 中,我有一个包含一些 UserID 的数组。
即 userIDs[0] = 1234;用户 ID[1] = 2345;
现在我想构建一个查询,如果可能的话只进行一次 sql 调用以获得以下结果:
############################
# UserID # Exists #
############################
# 1234 # 0 #
# 2345 # 1 #
############################
是否有 sql 解决方案,或者我是否必须通过单独的调用来检查每个 ID?
感谢您的帮助!
要对照列表检查现有的 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
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);
//...
差不多就这些了。因为查询是一个字符串,所以您可以随意构建它:)
我想知道如何检查用户是否已经在数据库中。
在 PHP 中,我有一个包含一些 UserID 的数组。 即 userIDs[0] = 1234;用户 ID[1] = 2345;
现在我想构建一个查询,如果可能的话只进行一次 sql 调用以获得以下结果:
############################
# UserID # Exists #
############################
# 1234 # 0 #
# 2345 # 1 #
############################
是否有 sql 解决方案,或者我是否必须通过单独的调用来检查每个 ID? 感谢您的帮助!
要对照列表检查现有的 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
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);
//...
差不多就这些了。因为查询是一个字符串,所以您可以随意构建它:)