3

我正在尝试做以下事情:我有两个表:ReportImage (imageId, reportId, counter) 和 userReportedImages (imageId, userId)

我希望每个用户只能报告一次图像 - 这意味着首先我想检查'userReportedImages'中是否有一行带有值(imageId,userId),如果这样做什么都不做,否则创建一行带有值(imageId、reportId、counter)的“ReportImage”,如果这样的行已经存在(其他用户报告了该图像),那么我想提高计数器。

到目前为止,在检查相同的用户报告之前,我有以下声明:

INSERT INTO ReportImage VALUES (imageId,reportId,1) ON DUPLICATE KEY UPDATE counter = counter+1

这个声明工作正常。

我试图更改此语句以首先检查另一张表上是否存在该行,但我没有设法做到这一点,您能帮帮我吗?

4

3 回答 3

3

首先,您需要UNIQUE在 table 上定义约束或复合列主键ReportImage

ALTER TABLE ReportImage ADD CONTRAINT tb_uq UNIQUE(ImageID, ReportID)

试试这个,

INSERT INTO ReportImage(ImageID, ReportID, Counter)
SELECT  'imageID HERE' AS ImageID,
        'userID HERE' AS ReportID,
        1 AS Counter
FROM    userReportedImages a
        LEFT JOIN ReportImage b
            ON  a.imageId = b.imageId AND
                a.userId = b.ReportID AND
                a.imageID = 'imageID HERE' AND
                a.userID = 'userID HERE'
WHERE   b.imageId IS NULL OR 
        b.ReportID IS NULL
ON DUPLICATE KEY UPDATE counter = VALUES(counter) + 1
于 2013-03-24T15:40:00.920 回答
1

你可以尝试使用NOT EXISTS

insert into table2(`name`)
select * from (select 'name1' as name) tmp
where not exists(
  select ('x') from table1 where name = 'test1'
  );

SQL小提琴

于 2013-03-24T15:51:55.973 回答
0

插入触发器应该是您的解决方案: link

于 2013-03-24T15:29:53.820 回答