简体   繁体   中英

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:

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. The thing is, ON DUPLICATE KEY doesn't allow you to select a column instead. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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