简体   繁体   中英

MySQL UPDATE with subquery with group by

I have the following tables on MySQL:

**Elements**
+------+------------------+------------------+
+ Id   + Name             + referenced       +
+------+------------------+------------------+
+ 1    + element1         + NULL             +
+ 2    + element2         + NULL             +
+ 3    + element3         + NULL             +
+ 4    + element4         + NULL             +
+ 5    + element5         + NULL             +
+ 6    + element6         + NULL             +
+------+------------------+------------------+

**References**
+------+------------------+------------------+
+ Id   + Name             + type             +
+------+------------------+------------------+
+ 1    + element1         + 1                +
+ 2    + element1         + 2                +
+ 3    + element3         + 1                +
+ 4    + element3         + 2                +
+ 5    + element3         + 3                +
+ 6    + element4         + 1                +
+ 7    + element5         + 2                +
+ 8    + element5         + 3                +
+------+------------------+------------------+

The "referenced" column on "Elements" table should have 0 for no reference of its name on "References" table and 1 for at least one reference of its name on "References" table.

This result could be selected with the following query:

SELECT Elements.Id, Elements.Name, (References.Id is not null) as referenced FROM
    Elements 
LEFT JOIN 
    References ON Elements.Name = References.Name 
GROUP BY Elements.Name ORDER by Elements.Id;

+------+------------------+------------------+
+ Id   + Name             + referenced       +
+------+------------------+------------------+
+ 1    + element1         + 1                +
+ 2    + element2         + 0                +
+ 3    + element3         + 1                +
+ 4    + element4         + 1                +
+ 5    + element5         + 1                +
+ 6    + element6         + 0                +
+------+------------------+------------------+

But I could't find a way to update the "Elements" table with this result.

Any ideas?

UPDATE Elements e
LEFT JOIN References r ON e.OneName = r.OtherName
SET e.referenced = r.OtherName IS NOT NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM