[英]Select multiple columns from one table, get corresponding details from another table and insert these to another table
主表:包含所有詳細信息,如proper_ID 和proper_Name 等字段。
父表:有母親和父親的唯一 ID,不存在proper_ID 和proper_Name
子表:需要以與父表相同的順序插入proper_ID 和proper_Name 並避免重復條目。
Master_Table
---------------------------------------------------------------
Proper_ID | Proper_Name | Proper_Address | Proper_Phone |Proper_Zipcode
----------------------------------------------------------------
ABC_235 | Pansy Montgomery | 427 Preston Court| 1234| 5679
KWH_631 | Price Maxwell | 164 Conduit Boulevard| 8782| 7893
DEA_124 | Howard Kelly | 314 Agate Court| 3234| 1529
FAE_832 | Best Mcpherson | 325 Dorchester Road| 1582| 1861
Parent_Table
---------------------------------------------------
M_ID | F_ID | Picture_URL | Age_Group | Email
---------------------------------------------------
235| 832 | http://placehold.it/32x32| 45 | espinozastrickland@accruex.com
631| 124 | http://placehold.it/32x32| 50 | roycooke@concility.com
Output Expected:
Child_Table
---------------------------------------------------
Mother_ID | Mother_Name | Father_ID | Father_Name
---------------------------------------------------
ABC_235 | Pansy Montgomery | FAE_832 | Best Mcpherson
KWH_631 | Price Maxwell | DEA_124| Howard Kelly
select mt.proper_id, mt.proper_name from master_table mt, parent_table pt
where mt.proper_id in (pt.m_id, pt.f_id)
proper_id | proper_name
-------------------------
ABC_235 | Pansy Montgomery
FAE_832 | Best Mcpherson
KWH_631 | Price Maxwell
DEA_124| Howard Kelly
您可以使用CREATE ... SELECT
語句創建Child_Table
。 您需要將Parent_Table
JOIN
到Master_Table
兩次,一次獲取母親的詳細信息,一次獲取父親的詳細信息。 請注意,您應該使用 ANSI 連接語法,逗號連接已經被取代了很長時間。
CREATE TABLE Child_Table AS
SELECT m1.Proper_ID AS Mother_ID,
m1.Proper_Name AS Mother_Name,
m2.Proper_ID AS Father_ID,
m2.Proper_Name AS Father_Name
FROM Parent_Table p
JOIN Master_Table m1 ON SUBSTRING_INDEX(m1.Proper_ID, '_', -1) = p.M_ID
JOIN Master_Table m2 ON SUBSTRING_INDEX(m2.Proper_ID, '_', -1) = p.F_ID
然后你可以
SELECT *
FROM Child_Table
輸出:
Mother_ID Mother_Name Father_ID Father_Name
KWH_631 Price Maxwell DEA_124 Howard Kelly
ABC_235 Pansy Montgomery FAE_832 Best Mcpherson
如果你只想生成一個行對於給定的對M_ID
和F_ID
值,你可以放置一個UNIQUE
的指標Mother_ID, Father_ID
在Child_Table
在CREATE
語句,然后要么IGNORE
重復或REPLACE
它們:
CREATE TABLE Child_Table (UNIQUE(Mother_ID, Father_ID)) IGNORE
... -- as above
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.