我有三个表,t1
、t2
和 t3
。
表 1 包括“列表”以及通过 ID 与列表关联的图像。它们都是通过查看类型
id: 1
postId: NULL
type: listing
id: 2
postId: NULL
type: listing
id: 3
postId: 1
type: image
id: 4
postId: 1
type: image
id: 5
postId: 2
type: image
表 2 还包含列表和图像关联,如下所示:
id: 1
listingId: 1
type: imageasoc
imgId: 3
id: 2
listingId: 1
type: imageasoc
imgId: 4
id: 3
listingId: 2
type: imageasoc
imgId: 5
当t1.id
与t1.postId
匹配时,我想在t2
中添加一个新行,其中将包含t1 .id
和 t1.postId
行的 id
,加上字符串“imageasoc
”(如您将在上面的例子)
我有下面的代码,但我需要它变成 INSERT INTO
语句,我已经尝试过,但语法/格式总是错误的:(
UPDATE t2
LEFT JOIN
t1
ON t1.id = t1.postId
SET t2.listingId = t1.id, t2.type = 'imageasoc', t2.imgId = id of t1.postID
WHERE t1.type = 'image'
我希望我已经解释得足够多了,谢谢!
最佳答案
如果我理解正确,您可以使用 INSERT...SELECT 语句来执行此操作:
INSERT INTO t2(listingId, type, imgId)
SELECT t1.id, 'imageasoc', t1.postId
FROM t1
WHERE t1.id = t1.postId
AND t1.type = 'image';
关于MySQL:如果 t1.row1 = t1.row2 插入 t2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37866484/