I have the following table definitions:
Table public.messages:
| Column | Type | Collation | Nullable | Default |
|---|---|---|---|---|
| ip | text | |||
| msg | text | |||
| ignore | boolean |
Table public.host:
| Column | Type | Collation | Nullable | Default |
|---|---|---|---|---|
| ip | text | |||
| name | text |
Yes, I could set type as IP for the ip, but for this example it doesn't matter.
I run this query:
SELECT *
FROM messages
LEFT JOIN host ON messages.ip = host.ip;
And get this result:
| ip | msg | ignore | ip | name |
|---|---|---|---|---|
| 1.1.1.1 | Test1 | 1.1.1.1 | host1 | |
| 1.1.1.2 | Test2 |
Sample data can be found here: https://dbfiddle.uk/3LTo9shO
I want to update all rows where there is no host name to set ignore to true.
So basically, just the ignore column for this result:
SELECT *
FROM messages
LEFT JOIN host ON messages.ip = host.ip
WHERE host.name IS NULL;
| ip | msg | ignore | ip | name |
|---|---|---|---|---|
| 1.1.1.2 | Test2 |
I can do an update for the row that does have a host name. When I set the value, everything works:
UPDATE messages
SET ignore = FALSE
FROM host
WHERE messages.ip = host.ip AND host.name IS NOT NULL;
UPDATE 1
SELECT *
FROM messages
LEFT JOIN host ON messages.ip = host.ip;
| ip | msg | ignore | ip | name |
|---|---|---|---|---|
| 1.1.1.1 | Test1 | f | 1.1.1.1 | host1 |
| 1.1.1.2 | Test2 |
However, setting true for those that don't have a host name doesn't work.
UPDATE messages
SET ignore = TRUE
FROM host
WHERE messages.ip = host.ip AND host.name IS NULL;
UPDATE 0
I tried with a LEFT JOIN, but then everything was updated:
UPDATE messages
SET ignore = TRUE
FROM messages m
LEFT JOIN host h ON m.ip = h.ip
WHERE h.name IS NULL;
UPDATE 2
SELECT *
FROM messages
LEFT JOIN host ON messages.ip = host.ip;
| ip | msg | ignore | ip | name |
|---|---|---|---|---|
| 1.1.1.1 | Test1 | t | 1.1.1.1 | host1 |
| 1.1.1.2 | Test2 | t |
How can I update just rows without a host name?
UPDATE messages s SET ignore=TRUE FROM messages m LEFT JOIN host h ON m.ip = h.ip WHERE m.ip = s.ip and h.name IS NULL;(dbfiddle.uk/N2wNIUIG)UPDATE messages s SET ignore=TRUE WHERE not exists(select ip from host h where h.ip=s.ip);