一個sql相同資料合併問題

來源:互聯網
上載者:User
我現在有個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了 也沒問題的吧

沒有問題,有問題(取出的項不對)時再加
顯然是加的越多效率越低

沒有問題,有問題(取出的項不對)時再加
顯然是加的越多效率越低

恩 謝謝版主

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.