我在MySQL中有三个表:wp_usermeta,directory_department和directory_departmentmemebership
Directory_departmentmembership
| employee_id|department_id|
|:-----------|------------:|
| 1 | 2 |
| 2 | 1 |
| 3 | 3 |
directory_department
| department_id|department_name|
|:----------- |--------------:|
| 1 | Deans |
| 2 | MBA |
| 3 | Fiance |
wp_usermeta:
| employee_id| meta_key | meta_value |
|:-----------|--------------:|:------------:|
| 1 |department_id | 2 |
| 2 |department_id | 1 |
| 3 |department_id | 3 |
| 1 |department_name| |
| 2 |department_name| |
| 3 |department_name| |
如何引用directory_department以根据meta_value字段中的department_id值插入正确的department_name?
答案 0 :(得分:0)
您可以使用SQL函数为每个id获取正确的名称......
CREATE FUNCTION [dbo].[fn_department](@id INT)
RETURNS VARCHAR(300)
AS
BEGIN
declare @department_name varchar(300)
select @department_name = department_name from directory_department where department_id = @id
RETURN @department_name
END
--And call it like this...
INSERT INTO wp_usermeta (id,department_name)
select id, dbo.fn_department(id) as department_name