简体   繁体   中英

How to insert values into a column in table B based on values in table A

I'm fairly new to SQL and only know basic commands right now. I'm trying to get a value for a column 'position' in table 'role' based on the value of column 'salary' in table 'payroll'.

Table 'role' and 'payroll' contain three common columns 'employee_ID', 'first_name' and 'last_name' with common values. I want to use another column 'salary' in table 'payroll' to determine the output for column 'position' in table 'role'.

For example, if the 'salary' column in table 'payroll' has a value less than 2000, I want the 'position' column in table 'role' to display 'janitor'.

This is what I'm using.

update role 
set position = 'janitor' 
where (select salary from payroll) > 2000 

And this is the error I'm getting.

#1242 - Subquery returns more than 1 row

I would really appreciate some help.

MySQL doesn't use a FROM keyword when doing an UPDATE from a query.

The MySQL syntax is this (parts in square-brackets are optional, parts in angle-brackets are placeholders):

UPDATE <table_references>
SET <assignment_list>
[WHERE <where_condition>]

-- <table_references> is defined as:
tableName1 [ AS <alias1> ] [ <join_operator> tableName2 [ AS <alias2> ] ON <join_criteria> ] [...]

So try this:

UPDATE
    role AS r
    INNER JOIN payroll AS p ON p.employee_id = r.employee_id
SET
    position = 'janitor'
WHERE
    p.salary > 2000

Another approach is to use a temporary-table with a WHERE IN predicate:

CREATE TEMPORARY TABLE employeeIds ( employeeId int NOT NULL );
INSERT INTO employeeIds ( employeeId )
SELECT employee_id FROM payroll WHERE salary > 2000;

UPDATE
    role
SET
    position = 'janitor'
WHERE
    employee_id IN ( SELECT employee_id FROM employeeIds );

The temporary table employeeIds will be deleted when you disconnect from the database - I assume you're using MySQL Workbench or similar. I don't know what the connection lifetime semantics are when using a web-based tool like phpMyAdmin, however.

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