I’ve been muddling through using MySQL for some time, but it’s still not really ‘in’ my brain yet, so I’m hoping I can make myself understood here, and that someone else can help me clear this particular cerebral mire of mine. 🙂
I have two MySQL tables, writers and abstracts, and an intersection table writer_abstract that joins them in a many-to-many relationship.
In the abstracts table, there’s a field accepted (a boolean) to indicate whether or not a certain abstract has been accepted for publication. Similarly, in the writers table, there is a field published (also a boolean) that indicates whether or not an author has had anything published (or accepted for publication).
The intersection table is very simple: it has an auto-incrementing id field, a writer_id field, and an abstract_id field. I can select back and forth between writers and abstracts using the intersection table without problems.
When an abstract is accepted or rejected, abstracts.accepted is set to either TRUE or FALSE.
What I would like to do is, in a single MySQL statement, update writers.published in all rows and set it to TRUE if there are any abstracts by that author whose accepted field is TRUE. But I can’t figure out how to phrase the UPDATE statement to get it to work.
My best efforts are something like this:
UPDATE writers LEFT JOIN
( SELECT abstracts.id AS aid, abstracts.accepted AS aacc FROM writer_abstract
LEFT JOIN abstracts ON writer_abstract.abstract_id = writers.id
WHERE aacc = TRUE AND writers.id = writer_abstract.author )
AS res
SET published = TRUE
Obviously, this doesn’t work (I have an error in my syntax near SET published = TRUE). But this can’t be something that isn’t fairly easily done, surely?!
Any help much appreciated! 🙂
Update
Based on KingFisher’s reply, here is the version that actually did what I wanted (note the RIGHT JOIN instead of the LEFT JOIN—the former naturally affected all rows in writers, which wasn’t what I wanted):
UPDATE writers RIGHT JOIN
( SELECT author, accepted FROM writer_abstract
LEFT JOIN abstracts ON writer_abstract.abstract_id = writers.id
WHERE accepted = TRUE )
AS res ON res.author = writers.id
SET published = TRUE
You should have
onclause with join ofwriterstable and yoursubquery.