MySQL:IF t1.row1 = t1.row2 INSERT INTO t2

时间:2016-06-16 18:11:24

标签: mysql

我有三个表,t1t2t3

表1包括“列表”以及通过ID与列表相关联的图像。通过查看type

来识别它们
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.idt1.postId匹配时,我想在t2中添加一个新行,其中包含t1.idid t1.postId行,加上字符串“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'

我希望我已经解释得足够多了,谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解正确,可以使用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';