我現在有個A表, 是這樣的 大家可以先跳過表 看下一句我想要什麼
name cart
黃鑫 壞人&同學
盧秀秀 同學
劉毅 朋友&同學
我現在要建立B表把A表的cart另存進來 B表像這樣
id cartname
1 同學
2 朋友
3 壞人
也就是資料去重存入到新的表中 請問這該用怎樣的代碼來完成呢
回複討論(解決方案)
不明白樓主講的兩個表的關係,也不清楚樓主的意圖
建議直接用指令碼來處理這個問題,基本上無法用一條SQL解決(實際上也不建議這樣)
程式定期執行相關處理邏輯,然後把最新資料插入到B表,至於去重操作,指令碼邏輯很好處理就不多說了
insert into test(cartname)select cart from userinfo group by cart;
我弄了半天 就像是上邊這樣的 不過還有個&符號去重的問題
其實就是把A表裡的分類標籤欄位 去重移入到新的表裡
select substring_index(cart,'&',1) from A表
union
select substring_index(substring_index(cart,'&',2),'&',-1) from A表
union
select substring_index(substring_index(cart,'&',3),'&',-1) from A表
套紅的重複若干遍
INSERT INTO table_b( cartname )
(
SELECT DISTINCT (cart) FROM table_a
)
&符號分割的部分也需要去重的話,用PHP指令碼來處理效率可能會高一點
select substring_index(cart,'&',1) from A表
union
select substring_index(substring_index(cart,'&',2),'&',-1) from A表
union
select substring_index(substring_index(cart,'&',3),'&',-1) from A表
套紅的重複若干遍
好吧 版主就是版主 用你給的代碼已經成功了, 不過我只執行了一次 好像沒什麼問題了 謝謝你版主
$intosql="insert into 表B(cart)select substring_index(cartname,'&',1) from 表Aunionselect substring_index(substring_index(cartname,'&',2),'&',-1) from 表Aunionselect substring_index(substring_index(cartname,'&',3),'&',-1) from 表A";mysql_query($intosql);
你現在的 cart 中只有一個'&',但以後也可能有多個
union
select substring_index(substring_index(cart,'&', 3),'&',-1) from A表
的個數應多於'&'的個數,這樣才不易出錯
注意那個 3 是順號,要逐一遞增
你現在的 cart 中只有一個'&',但以後也可能有多個
union
select substring_index(substring_index(cart,'&', 3),'&',-1) from A表
的個數應多於'&'的個數,這樣才不易出錯
注意那個 3 是順號,要逐一遞增
哦 那就是有幾個&符號就加幾句
union
select substring_index(substring_index(cartname,'&',[color=#0000FF]3),'&',-1) from 表A[/color]
是嗎 然後那個藍色數字是遞增的 那如果是1個&符號的話 就一句select substring_index(cart,'&',1) from A表就可以了嗎 那我是直接按你的用到3了 也沒問題的吧
沒有問題,有問題(取出的項不對)時再加
顯然是加的越多效率越低
沒有問題,有問題(取出的項不對)時再加
顯然是加的越多效率越低
恩 謝謝版主