I have a query that retrieves data every day for a lot of different posts. Before inserting that for each post, I want to check if the data is not the same as the day before for that post.
Table post_metrics:
| 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
So lets say the system wants to insert data for 2017-01-12 for post with id 123 It needs to check if value1 is not the same as the day before (40)
I found this stack answer which I think got me in the right direction: MySQL: Insert record if not exists in table in which this is suggested (rewrote it to fit my example table):
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
)
Now this works great and does the job if I didnt find this problem:
My actual Query:
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(), 94997, 61475, 87611, 5382, 2677, 1818, 2052, 1890, 577, 540, 53, 21955, 0, 959.13, 0, 'weak', 'normal rates', 0.00086213908092721, 0.0093859292395283, 0, 123) AS tmp
WHERE NOT EXISTS (
SELECT `post id`, `impressions` FROM `post metrics minutes` WHERE `post id` = 123 AND `impressions` = 94997)
This returns the error:
Duplicate column name '0'
which comes from the multiple values zero I try to select on row 3. How could I fix this?