Reputation: 6346
I would normally do this programmatically, but I'm in a learning mood today... I looked around SO but didn't find anything exactly like my problem.
I have two tables item
, person
, and a third that contains associations, item_person
. Not everyone has an item so the association doesn't always exist. Now, I want to maintain a status
column in the item
table which is partly based on whether an item is associated with a person. So...
Table: item
item_id
description
status
Table: person
person_id
name
Table: item_person
item_id
person_id
Imagines that I want to UPDATE
the item status to 1
if an association exists in item_person
...
Is there a single MySQL query that can handle this?
Is there a single MySQL query that can do an UPDATE
if an association doesn't exist in item_person
.
Upvotes: 2
Views: 913
Reputation: 37388
-- If the association exists...
update item i
join item_person ip
on ip.item_id = i.item_id
set i.status = 1
-- If the association does not exist...
update item i
left join item_person ip
on ip.item_id = i.item_id
set i.status = 0
where ip.item_id is null
Upvotes: 3
Reputation: 34657
Note, both queries are untested, as I don't have access to mysql from here and you haven't given a fiddle. Feel free to leave a comment if you need help debugging though.
Upvotes: 0