简体   繁体   中英

SELECT a value multiple time in SQL

I have a code in PHP where I want to display multiple times values, and so, even if these values are the same between them. My code is simple :

$sql = "SELECT photo from table WHERE username IN ('1','2','2') ORDER BY id DESC ";

$res = array();
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
  array_push($res, $row['photo']);
}
echo json_encode($res);

But this code only display (in json) an array of two values (because the values of photo of the username 2 are the same). What I want to achieve is to make an array with the exact same number of values of the number of username I defined WHERE username IN ('1','2','2') (so here, 3 values). I hope you understood me, thanks for helping me !

You would use left join :

select t.photo
from (select '1' as username union all select '2' union all select '3'
     ) u left join
     table t
     on t.username = u.username
order by t.id desc;

Note this will return rows, even when the user name does not exist. If you want to filter those rows, remove the left so you are doing an inner join.

I think what you're after is to list even the duplicates in the end result. As your SQL will only retrieve the unique items, the idea would be to include the username in the SQL result set. Then use the original list of user names ( $userNames ) and add in the photo for each of them.

I've used mysqli_fetch_all() to simplify the process of fetching all of the data, then used array_column() to make the username the key for the photos.

$userNames = array(1,2,2);
$sql = "SELECT username, photo 
          from table 
          WHERE username IN ('".implode("','", $userNames)."') 
          ORDER BY id DESC ";

$res = array();
$result = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($result, MYSQLI_ASSOC);

$photos = array_column($photos, "photo", "username");
foreach ( $userNames as $user ) {
    if ( isset($photos[$user])) {
        $res[] = $photos[$user];
    }
    else    {
        $res[] = '';
    }
}
echo json_encode($res);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM