I have 2 tables I want to merge into a third table I would like to do it purely as a MySQL query rather than selecting the rows and using PHP while() to build the third table.
Table 1 contains the following
ID Name
1 A
2
3
Table 2 contains the following
ID Desc
10
15 B
20
I want to write a query statement to produce the following combined table, but I only want the new Desc to contain the non-blank value from Name in Table 1 or Desc in Table 2, with Table 2 getting precedence over Table 1 in the event both tables contain a non-blank
ID1 ID2 Desc
1 10 A
1 15 B
1 20 A
2 10
2 15 B
2 20
3 10
3 15 B
3 20
Is this do-able as a MySQL query I should I use a PHP method?
Thanks.
insert into TableThree (id1, id2, Descr)
select
T1.id,
T2.id,
case LENGTH(TRIM(T2.Descr))
when 0 then T1.Name
else T2.Descr
end
from TableOne T1, TableTwo T2
order by 1, 2
想想,你需要这个......
select t1.id as id1, t2.id as id2, if(length(t2.name), t2.desc, t1.name) as desc from t1,t2;
you could do it like this:
SELECT a.ID as ID1, b.ID as ID2, (CASE WHEN b.Desc is not null THEN b.Desc ELSE a.Name END) as Desc from Table1 a full join Table2;
But this is untested ... so good luck.
Regards
parascus
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.