我试图像这样进行查询...
INSERT INTO article_keyword (article_id, keyword_id, strength)
SELECT ?, keyword.keyword_id, strength_table.strength FROM keyword
INNER JOIN (SELECT 5 AS strength, 'keyword1' AS keyword) AS strength_table
ON strength_table.keyword=keyword.keyword
WHERE keyword IN ('keyword1', 'keyword2', 'keyword3');
在上面的INNER JOIN
...我需要从PHP中的数组SELECT
看起来像...... $array = ['keyword1' => 9, 'keyword2' => 11, 'keyword4' => 13];
,其中值是强度,关键是关键字。基本上......我想INNER JOIN
一个临时/动态表,其中包含基于该数组的字段keyword
和strength
。我不需要PHP / PDO的帮助,但我如何在那里放一张桌子?有没有一种简单的方法来生成我可以SELECT
来自哪个表格?
执行的SQL有效......它在article_keyword中插入一行:('some article id', 5, 'keyword1 id')
。
TL; DR:我可以根据数组将(SELECT 5 AS strength, 'keyword1' AS keyword)
更改为表吗?
答案 0 :(得分:2)
您可以使用UNION ALL
在子查询中构建内联表:
INSERT INTO article_keyword (article_id, keyword_id, strength)
SELECT ?, keyword.keyword_id, strength_table.strength
FROM keyword
INNER JOIN (
SELECT 9 AS strength, 'keyword1' AS keyword
UNION ALL
SELECT 11 AS strength, 'keyword2' AS keyword
UNION ALL
SELECT 13 AS strength, 'keyword4' AS keyword
) AS strength_table
ON strength_table.keyword=keyword.keyword
另一种方法是将值插入临时表。然后在INSERT语句中使用该表:
CREATE TEMPORARY TABLE tmp_strength_table (strength INT, keyword VARCHAR(50));
INSERT INTO tmp_strength_table (strength, keyword) VALUES
( 9, 'keyword1'),
(11, 'keyword2'),
(13, 'keyword4');
INSERT INTO article_keyword (article_id, keyword_id, strength)
SELECT ?, keyword.keyword_id, strength_table.strength
FROM keyword
INNER JOIN tmp_strength_table AS strength_table
ON strength_table.keyword=keyword.keyword