簡體   English   中英

基於某種條件的插入(Mysql)

[英]Insertion based on some condition (Mysql)

我有帶有字段ID,名稱的表標簽

在前端,用戶輸入與相應產品關聯的文本區域中逗號分隔的標簽

因此,在插入期間,我想將不在標簽表中的標簽添加到標簽表中。

所以所有工作正常,但問題是我想將不在標簽表中的特定標簽添加到表中

例如:考慮表格

產品名稱:橙汁描述:橙汁的描述。 標簽:水,果汁,飲料

所以我想將那些標簽添加到表中不存在的標簽表中。 例如,桌子上有水和飲料,果汁里沒有,所以只能在標簽表中加果汁。

您可以有一個臨時表,叫做temptags,在此處插入您在textarea中輸入的標簽,然后在此處插入臨時標簽,以便在標簽表中檢查它們是否不存在后插入它們,如下所示: http ://sqlfiddle.com/#!2 / c2855 / 1

CREATE TABLE tags (
  tag VARCHAR(32)
);

INSERT INTO tags VALUES
('Water'),
('Drinks');


CREATE TABLE temptags (
  tag VARCHAR(32)
);

INSERT INTO temptags VALUES
('Water'),
('drinks'),
('juices');


INSERT INTO tags SELECT tag FROM temptags WHERE UCASE(tag) NOT IN (SELECT UCASE(tag) FROM tags);

如果使“名稱”列唯一,則可以使用INSERT IGNOREINSERT ... ON DUPLICATE KEY UPDATE ...

您可以使用explode表單標簽將其作為數組,然后將數組的每個值與已存儲的標簽進行比較。 因此,您將能夠找到新的並將其INSERT表中。

嘗試這個

$part=substr($string,strripos($string,"Tags:")+5); // to get the tags list after "Tags:". 

$part=explode(",",$part);


$con=mysqli_connect("host", "user", "password", "db");

$query="select tag from tag"; 

if(!($result=mysqli_query($query))){
    //error
}
$table_tags=array();
while($row=mysqli_fetch_assoc($result)){
    $table_tags[]=$row['tag'];
}

$new_tags=array_diff($part,$table_tags);

//prepare query
$query="insert into tags values ";
foreach($new_tags as $tag){
    $query=."(".$tag."), ";
}
$query=substr($query,0,-1); //remove the last comma

if(!mysqli_query($con,$query)){
    //error
}
//else success

使用INSERT IGNORE INTO表

http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html

還有INSERT…ON DUPLICATE KEY UPDATE語法,您可以在dev.mysql.com上找到說明。

暫無
暫無

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

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