2015年1月7日 星期三

MYSQL SELECT完的資料放入INSERT INTO


正確與法

Insert Into prodclass (LarSeq,LarCode,MidSeq,MidCode) Select LarSeq,LarCode,max(MidSeq)+1,'12345' From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1)"

如果是以下這種語法會報錯

You have an error in your SQL syntax

Insert Into prodclass (LarSeq,LarCode,MidSeq,MidCode) Values((Select LarSeq From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1)),(Select LarCode From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1)),(Select max(MidSeq)+1 as newValue From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1)),1234)

INSERT INTO 中 如果採用 SELECT 則無法使用 VALUES

2015年1月6日 星期二

MySQL 欄位合併與字串合併


將兩個資料表的某一欄位合併輸出成一個欄位

table_1
t1_name
a
b
c
d

table_2
t2_name
e
f
g


newName
a
b
c
d
e
f
g 

語法
SELECT t1_name as newName FROM table_1 2 union all SELECT t2_name FROM table_2 order by newName 

如果是單一資料表的兩個欄位要合併的話
語法如下

Select distinct LarCode as NewColumn From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1) union all Select concat(concat(MidSeq,'.'),MidCode) From prodclass Where LarSeq = (Select LarSeq From prodclass Where ClassId = 1)

concat(str1,str2) 字串合併
union all 欄位合併