开发者

Insert rows into many-to-many table but avoid FK lookup/subquery

I have a many2many table in my DB that gets thousands of pushes every hour. Let's say it looks like:

+-----------------------+
| pageNotes             |
+-----+--------+--------+
| id  | pageid | noteid |
+-----+--------+--------+
| 1   | 37583  | 385839 |
| 2   | 37583  | 385840 |
| ... | ...    | ...    |
+-----+--------+--------+

When I want to update the table, I only have the page URL (which is in the table "pages", which has pageid as its FK in the pageNotes table). I really want to avoid having to buffer tens of thousands of records to have the PK lookup in my code so I'm kinda curious wether there's another way - except for subqueries - to achieve this.

Currently, the query looks like:

INSERT INTO 
     `pageNotes ` (id,pageid,noteid) 
     VALUES ('',
       (SELECT id FROM pages WHER开发者_高级运维E url='http://www.test.com/index.html')
       ,385841);

This is not usable of course because if the page doesn't exist, the query will fail. What I'm looking for is a way to either fetch the pk OR insert the row in the FK table.


You can simplify the query as:

INSERT INTO `pageNotes` (id, pageid, noteid)
SELECT '', p.id, 385841
    FROM pages p
    WHERE url = 'http://www.test.com/index.html';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜