簡體   English   中英

Mysql單獨用sql語句插入多個用逗號分隔的值的行

[英]Mysql Insert Multiple Rows with comma separated values with sql statement alone

打算執行多個sql插入語句,而不將它們運行到node.js等中的某種循環中。

典型的sql語句如下所示。

INSERT INTO session_speaker(session_id, speaker_id) VALUES(?, ?);
INSERT INTO session_speaker(session_id, speaker_id) VALUES(?, ?);

要么

INSERT INTO session_speaker(session_id, speaker_id) VALUES(?, ?), (?, ?);

普通的node.js循環如下所示。

for (var i = 0; i < request.body.length; i++) {
    queryRequest.sql += "INSERT INTO session_speaker(session_id, speaker_id) VALUES(?, ?);";
    queryRequest.values.push(request.body[i].id, request.params.id);
}

意向/問題:

探索一種可能的方式,將request.body傳遞給一個智能SQL,該SQL接受數組本身或用逗號分隔的值列表,然后從那里插入多行而沒有node.js循環。

request.body看起來像這樣(可更改以滿足要求)

[
  {
    "id": 12
  },
  {
    "id": 34
  }
]

是的,這是可能的。 看看這個參考。 https://dev.mysql.com/doc/refman/5.7/en/json.html

這是您可以做的。

  1. 選擇您的對象數據
  2. 轉換為數組
  3. 取消嵌套數組(在列視圖中使用make array)的引用: MYSQL中的UNNEST函數(如POSTGRESQL) ,該函數需要一個字符串,因此將您的數據(array)轉換為data(字符串)是這里的參考: 是否有與PostgreSQL等效的MySQL array_to_string
  4. insert into select參考中使用insert into selecthttps : //dev.mysql.com/doc/refman/5.1/en/insert-select.html

最后,您的代碼如下所示:

insert  into session_speaker(session_id, speaker_id)  
select unnest_mysql ( arrayToString (dataTOArray( stringtojson (json_string) ) ) )

json_string =這是您來自php的數據

dataTOArray =此函數將您的數據轉換為mysql json轉換為數組

dataTOArray =將數組轉換為字符串ex。 [1,2,3]'1,2,3' unnest_mysql =您的字符串到行數據

 string '1,2,3'
 --view like 

 |-------String-----|
 |---------1--------|
 |---------2--------|
 |---------3--------|
 |----------- ------|
 So when you insert this , it will become row in your table

注意:將我的函數更改為MySQL特定的函數。

我認為這使我離尋找的東西更近了。

https://github.com/felixge/node-mysql/issues/814

根據dougwilson的評論以及他對嵌套數組的解決方案,我可以簡單地將多對象數組傳遞給查詢,它將立即插入多個記錄。

var currentLogs = [
  [ 'Server', 'Socketio online', 'Port 3333', '2014-05-14 14:41:11' ],
  [ 'Server', 'Waiting for Pi to connect...', 'Port: 8082', '2014-05-14 14:41:11' ]
];

pool.query('INSERT INTO logs_debug (socket_id,message,data,logged) VALUES ?', [currentLogs])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM