简体   繁体   English

一种查询或执行sql语句的快速方法

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

I have a table of hashtags that looks something like this: 我有一个标签表,看起来像这样:

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

And a table of topics that have had these hashtags tagged to them like so: 带有这些标签的标签的主题表如下所示:

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

I've been trying to make a MYSQL statement (to no success) that can do the following in pseudocode: 我一直在尝试做一个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');

Basically I need to get the ID of the hashtag name, if it does not exist, then insert it and get the last inserted id, then use these values to record it into the hashtag_topics table. 基本上,我需要获取主题标签名称的ID(如果它不存在),然后将其插入并获取最后插入的ID,然后使用这些值将其记录到hashtag_topics表中。 The thing is, ON DUPLICATE KEY doesn't allow you to select a column instead. 关键是,ON DUPLICATE KEY不允许您选择列。 Is there another way I can do this, or is it just faster to use multiple queries? 还有另一种方法可以执行此操作,还是使用多个查询更快? (I feel like it's not though). (我感觉不是)。 I really don't want to have to do: 我真的不想做:

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

You can't do all of that in one query. 您无法在一个查询中完成所有这些操作。 Just use multiple queries. 只需使用多个查询。 It will not create excessive load because modern databases and file systems are excellent at caching. 因为现代数据库和文件系统在缓存方面非常出色,所以不会造成过多的负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM