Question

I've got two tables like this:

ips(ip PRIMARY KEY, device)
users_have_ips(user, ip FOREIGN KEY REFERENCES ips)

An ip can belong either to a device or an user. So I have to check the ip doesn't belong to an user while updating ips.device. Analog there is to check the ip doesn't belong to an device while updating/inserting users_have_ips.

I would try to solve this using the following meta code:

CREATE TRIGGER tr_ips_ip4device
BEFORE UPDATE ON ips
FOR EACH ROW
BEGIN
    IF NEW.device IS NOT NULL
            AND NEW.ip IN (SELECT ip FROM users_have_ips)
    THEN
        RESTRICT -- with message "ip already belongs to an user"
    END IF;
END

CREATE TRIGGER tr_users_have_ips_freeip
BEFORE INSERT+UPDATE ON users_have_ips
FOR EACH ROW
BEGIN
    IF NEW.ip IN (SELECT ip FROM ips WHERE device IS NOT NULL)
    THEN
        RESTRICT -- with message "ip already belongs to an device"
    END IF;
END

The main problem I have is the RESTRICT. How can I abort the changes like on incorrect foreign keys? Another one is the SELECT-statement in triggers.

Is there a better way (maybe without triggers) to solve this?

No correct solution

OTHER TIPS

I think you might mean to use ROLLBACK instead of RESTRICT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top