I was wondering how I can check whether users are already in the database or not.
In PHP I have an array with some UserIDs. ie userIDs[0] = 1234; userIDs[1] = 2345;
Now I wanted to build a query to make just one sql call if possible to get following result:
############################
# UserID # Exists #
############################
# 1234 # 0 #
# 2345 # 1 #
############################
Is there a sql solution or do I have to check each ID with a seperate call? Thank you for your help!
To check existing id
s against a list you can do
select userId, userId in (2345,5678) as `exists`
from your_table
order by userId
But to check if a list of id
s is in the DB you can do
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:
you build up your query in PHP which is string.
$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);
//...
That is pretty much it. Because the query is a string, you can build it up just like you want to have it :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.