简体   繁体   中英

sql select from table then compare with other table in one statement

I have to tables in one database.

  1. users
  2. user_activate

I have to variables in php

  1. $username = foo;
  2. $key = jas823k123ksd34324;

Now I want to select from the table users the attribute user_id where user_username == $username

I do this with this statement

$sql = "SELECT user_id FROM users WHERE user_username = '$username'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result)){
    $user_id = $row['user_id'];
}

Now I want to select from the table user_activate the attribute user_activate_key where user_activate_key == $key;

For this I use this statement:

$sql2 = "SELECT user_activate_key FROM user_activate WHERE user_activate_key = '$key'";
$result2 = mysqli_query($db, $sql2);
while($row = mysqli_fetch_assoc($result)){
    $user_key = row['user_activate_key'];
}

Can I do both statements in one statement?

As you've written it, two seperate queries is the correct way to do it. But I suspect that there's some kind of relationship between users and user_activate that might make what you're asking for make sense. Assuming that a user_activate_key is tied to a specific user_id , you could do something like the following:

select users.user_id, ua.user_activate_key
from users u
left join user_activate ua
    on u.user_id = ua.user_id
    and ua.user_activate_key = '$key'
where u.username = '$username'

The LEFT JOIN means that the user will be shown even if there isn't a matching user_activate_key record.

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