2013-10-29 110 views
-1

我在MySQL有三個表從另一個表插入方式:wp_usermeta,directory_department和directory_departmentmemebershipSQL通過參考表

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

只需使用語句:'INSERT INTO ... SELECT ... FROM ...':HTTPS://dev.mysql。 com/doc/refman/5.5/en/insert-select.html還是要求完整的INSERT和SELECT查詢? – feeela

回答

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 
+0

哇,太快了!我現在正在嘗試。謝謝! – user2920496

+0

我對mysql相當陌生。 [dbo]是什麼意思? – user2920496

+0

dbo(數據庫所有者)是默認模式,所有表和對象(存儲過程和函數)通常使用此模式創建。 – Hiram