簡體   English   中英

一種查詢或執行sql語句的快速方法

[英]One query or quick way to execute sql statement

我有一個標簽表,看起來像這樣:

TABLE: hashtags
hashtag_id      hashtag_name - UNIQUE
1                 apples
2                 oranges
3                 life

帶有這些標簽的標簽的主題表如下所示:

TABLE: topic_hashtags, unique index on hashtag_id and topic_id
topic_hashtag_id     hashtag_id    topic_id   
1                       1             2          
2                       3             18
3                       3             30
4                       2             15

我一直在嘗試做一個MYSQL語句(沒有成功),該語句可以用偽代碼執行以下操作:

INSERT INTO topic_hashtags (hashtag_id, topic_id) 
VALUES(SELECT LAST_INSERT_ID(INSERT INTO hashtags (hashtag_name) VALUES('somehashtag') 
ON DUPLICATE KEY SELECT hashtag_id FROM hashtags WHERE hashtag_name = 'somehashtag'), 'x');

基本上,我需要獲取主題標簽名稱的ID(如果它不存在),然后將其插入並獲取最后插入的ID,然后使用這些值將其記錄到hashtag_topics表中。 關鍵是,ON DUPLICATE KEY不允許您選擇列。 還有另一種方法可以執行此操作,還是使用多個查詢更快? (我感覺不是)。 我真的不想做:

SELECT id from hashtags
if mysqli_num_rows($result) == 1):
use the id and insert
endif;
else
insert
mysqli_insert_id
use that id and insert

您無法在一個查詢中完成所有這些操作。 只需使用多個查詢。 因為現代數據庫和文件系統在緩存方面非常出色,所以不會造成過多的負載。

暫無
暫無

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

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