我有一个查询,每天检索很多不同帖子的数据。在为每个帖子插入之前,我想检查数据是否与该帖子前一天的数据不同。
表post_metrics:
$prodAvail = $db->query($sqlProdPage);
<?php while($product= mysqli_fetch_assoc($prodAvail)) : ?>
因此,假设系统想要为2017-01-12插入ID为123的帖子,需要检查value1是否与前一天不同(40)
我发现这个堆栈的答案,我觉得我正朝着正确的方向前进: 建议使用MySQL: Insert record if not exists in table(重写它以适合我的示例表):
| id | date | value1 | value2 | etc...
| 123 | 2017-01-10 | 20 | 50 | more columns
| 123 | 2017-01-11 | 40 | 80 | more columns
| 124 | 2017-01-10 | 100 | 600 | more columns
| 124 | 2017-01-11 | 410 | 800 | more columns
现在这很有效,如果我没有发现这个问题,那就完成了工作:
我的实际查询:
INSERT INTO `post_metrics` (`id`, `date`, `value1`, `value2`)
SELECT * FROM (SELECT 123, now() 113, 84344, now()) AS tmp
WHERE NOT EXISTS (
SELECT `id`, `value1` FROM `post_metrics` WHERE `id` = 10156753760478438 AND `value1` = 84344
)
这将返回错误:
重复列名称&#39; 0&#39;
来自我尝试在第3行选择的多个零值。我怎么能解决这个问题?
答案 0 :(得分:2)
现在您从子查询创建别名tmp,默认情况下,如果未分配名称,则列名称将从值中派生。如果碰巧多次使用相同的值,则派生列名称将相同。
您需要做的就是命名子查询中的列(代码也变得更具可读性):
INSERT INTO `post metrics minutes` ( `date updated`, `impressions`, `reach`, `fan reach`, `viral reach`, `consumptions`, `consumers`, `engaged users`, `engaged fans`, `engagements`, `storytellers`, `negative feedbacks`, `video views`, `hours video view time`, `video length (sec)`, `video avg time watched`, `content quality`, `type alignment`, `neg.fdbck.rate unweighted`, `eng.rate unweighted`, `video completion rate unweighted`, `post id`)
SELECT * FROM (
SELECT
now() as 'date updated',
94997 as 'impressions',
61475 as 'reach',
87611 as 'fan reach',
5382 as 'viral reach',
2677 as 'consumptions',
1818 as 'consumers',
2052 as 'engaged users',
1890 as 'engaged fans',
577 as 'engagements',
540 as 'storytellers',
53 as 'negative feedbacks',
21955 as 'video views',
0 as 'hours video view time',
959.13 as 'video length (sec)',
0 as 'video avg time watched',
'weak' as 'content quality',
'normal rates' as 'type alignment',
0.00086213908092721 as 'neg.fdbck.rate unweighted',
0.0093859292395283 as 'eng.rate unweighted',
0 as 'video completion rate unweighted',
123 as'post id'
) AS tmp
WHERE NOT EXISTS (
SELECT *
FROM `post metrics minutes`
WHERE `post id` = 123 AND `impressions` = 94997
)