如何仅在WHERE COUNT(使用GROUP BY的子查询)= 1时更新值?

时间:2012-03-01 22:36:35

标签: mysql

我正在尝试将行值设置为1,当它是组中的唯一行时,只有一个查询。

当前表格(CATEGORY_BRAND):

|categoryId | brandId | featured |
|-----------+---------+----------|
| 1         | 100     | -1       |
| 1         | 101     | -1       |
| 1         | 102     | -1       |
| 2         | 100     | -1       |
| 3         | 110     | -1       |
| 3         | 111     | -1       |
| 4         | 102     | -1       |
| 5         | 101     | -1       |
| 6         | 100     | -1       |
| 6         | 110     | -1       |
| ...       | ...     | ...      |

希望结果(CATEGORY_BRAND):

|categoryId | brandId | featured |
|-----------+---------+----------|
| 1         | 100     | -1       |
| 1         | 101     | -1       |
| 1         | 102     | -1       |
| 2         | 100     | 1        |
| 3         | 110     | -1       |
| 3         | 111     | -1       |
| 4         | 102     | 1        |
| 5         | 101     | 1        |
| 6         | 100     | -1       |
| 6         | 110     | -1       |
| ...       | ...     | ...      |

(我最诚挚的道歉,如果这是重复,我找不到其他人这样做更新。)

1 个答案:

答案 0 :(得分:3)

这可能不是最高效的,但应该有效(尽管你应该先测试一下)。

UPDATE category_brand JOIN (
    SELECT categoryId
    FROM category_brand
    GROUP BY categoryId
    HAVING COUNT(categoryId) = 1)
  AS single_cbs USING(categoryId) SET category_brand.featured = 1;