我有以下MySQL表:
memo_words
+----+-----------------------+---------+
| id | current_definition_id | word_id |
+----+-----------------------+---------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 1 | 2 |
| 4 | 2 | 2 |
+----+-----------------------+---------+
words
+----+
| id |
+----+
| 1 |
| 2 |
+----+
definitions
+----+
| id |
+----+
| 1 |
| 2 |
+----+
definitions_words
+---------+---------------+----------+
| word_id | definition_id | position |
+---------+---------------+----------+
| 1 | 1 | 0 |
| 1 | 2 | 0 |
| 2 | 1 | 0 |
| 2 | 2 | 0 |
+---------+---------------+----------+
我希望对于从下面的查询返回的任何行,使用值别名position
更新相关的(definition_id、word_id)definitions_words.position
:
SELECT word_id, current_definition_id as definition_id, COUNT(*) as position
FROM memo_words
WHERE current_definition_id IS NOT NULL
GROUP BY current_definition_id, word_id;
+---------+---------------+----------+
| word_id | definition_id | position |
+---------+---------------+----------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 1 | 2 | 1 |
| 2 | 2 | 1 |
+---------+---------------+----------+
一个问题
因此,result此操作应如下所示:
definitions_words
+---------+---------------+----------+
| word_id | definition_id | position |
+---------+---------------+----------+
| 1 | 1 | 1 |
| 1 | 2 | 1 |
| 2 | 1 | 1 |
| 2 | 2 | 1 |
+---------+---------------+----------+
DDL:
CREATE TABLE memo_words( id int, current_definition_id int, word_id int, PRIMARY KEY(id));
INSERT INTO memo_words VALUES (1, 1, 1), (2, 2, 1), (3, 1, 2), (4, 2, 2);
CREATE TABLE words(id int, PRIMARY KEY(id));
INSERT INTO words VALUES(1), (2);
CREATE TABLE definitions(id int, PRIMARY KEY(id));
INSERT INTO definitions VALUES(1), (2);
CREATE TABLE definitions_words(word_id int, definition_id int , position int);
INSERT INTO definitions_words VALUES(1,1,0), (1,2,0), (2,1,0), (2,2,0);
2条答案
按热度按时间83qze16e1#
我将使用
join
和子查询来执行此操作:vd2z7a6w2#
SQLFIDDLE语言