简体   繁体   中英

SQL Selecting one record from two tables, then update it

I have two tables in my database, Users and Staff. Self explanatory I hope. Attributes common to both tables are:


| id | Reference | First_Name | Last_Name | Email |...

In my user.php file, there's a lot of functions used to update an attribute for a user's account. Currently it's very inefficient because I have had to split the queries to check if a user is in the Users table or the Staff table, then do the same thing in order to push any changes back to my database.

I'd like a single query to do the hard work of finding the record from two tables.

    //Check the USERS table first
    $LocateAccount__UsersTable_Query = $CTDatabase->prepare("SELECT * FROM Staff WHERE Reference='$Account_Reference'");
    $LocateAccount__UsersTable_Query-> execute();
    $LocateAccount__UsersTable_Count = $LocateAccount__UsersTable_Query->rowCount();

if ($LocateAccount__UsersTable_Count > 0){
    //Fetch the user's record
    // echo "USER IS USER";
      $Located_Account = $LocateAccount__UsersTable_Query->fetch(); 


  } else {
    //Account not found in USERS table, so check STAFF table
    $LocateAccount__StaffTable_Query = $CTDatabase->prepare("SELECT * FROM Staff WHERE Reference='$Account_Reference'");
    $LocateAccount__StaffTable_Query-> execute();
    $LocateAccount__StaffTable_Count = $LocateAccount__StaffTable_Query->rowCount();

    if ($LocateAccount__StaffTable_Count > 0){
      //Account has been found in the USERS table
      $Located_Account = $LocateAccount__StaffTable_Query->fetch(); 
      //Fetch the STAFF user's record
      // echo "USER IS STAFF";

    } else {
      echo 'An error message goes here..';
    }

Question 1: How can I find a user in either Users or Staff tables in one single query?

Question 2: How can I then UPDATE an attribute on a single entry in one of these tables in a single query?

Things I am looking into, using EXISTS, but I get errors when trying the code in Sequel Pro: SQL Data from One of Two Tables

Assuming 'Reference' column will have unique values across both the tables, you can use UNION operator to search both the tables with same value, eg:

select Reference, first_name, last_name from users where Reference = ?
UNION
select Reference, first_name, last_name from staff where Reference = ?

You can also update both the tables in one query using join , eg:

UPDATE users,staff SET table1.col=a,table2.col2=b
WHERE users.reference = ?;

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