Randomly getting the "Integrity constraint violation" sql error on saving entry
It's not a Craft bug.

The error means that the data in your craft_relations table is out of sync with the data in the your craft_elements table.  i.e. an ID exists in craft_relations.targetId that doesn't exist in craft_elements.id or visa-versa.

How it got that way is hard to say, but here are some common causes:


Someone manually edits database data without realizing the implications.
A database was imported into a MySQL box that only supported the MyISAM storage engine, which doesn't support foreign keys, so all of the foreign keys that Craft relies on to keep data consistent between tables are silently dropped.  If this is the case, you can use https://github.com/pixelandtonic/craft-fixfks to try and restore Craft's foreign keys.
A botched import/export script.
A plugin behaving poorly.


In the context of these two tables, if you want to find all rows that have a value in craft_relations.targetId that doesn't exist in craft_elements.id, the SQL would be similar to:

SELECT * FROM craft_relations r
LEFT OUTER JOIN craft_elements e
ON r.targetId = e.id
WHERE e.id IS NULL