mySQL查询,使用所有记录中的组合值更新每个记录
我们有两个表(comment和comment_标记),如下所示:mySQL查询,使用所有记录中的组合值更新每个记录,mysql,sql,Mysql,Sql,我们有两个表(comment和comment_标记),如下所示: mysql> describe comment; +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+
mysql> describe comment;
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| blogpost_id | int(11) | YES | | NULL | |
| comment_text | varchar(256) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
mysql> describe comment_tags;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| comment_id | int(11) | YES | | NULL | |
| tag | varchar(80) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
每个评论都可以有不同的标签。现在,我们希望将所有注释标记传播到同一博客帖子的所有注释。因此,本质上,我们希望每个博客帖子上的所有评论都有相同的comment_标签
我知道我们可以编写一个脚本或PL/SQL来实现这一点。但我想知道是否有一个mySQL查询可以做到这一点
是否可以使用一个mySQL查询将注释上的所有标记传播到同一篇博文的所有注释?假设您在
注释标记
表上有一个带有注释id的复合主键
和标记
字段(听起来您应该这样做),然后,您可以使用插入忽略:
insert ignore into comment_tags
select distinct c.id, ct.tag
from comment c
join comment c2 on c.blogpost_id = c2.blogpost_id
join comment_tags ct on ct.comment_id in (c.id, c2.id)
编辑
根据您的评论,您可以在查询中包含不存在
:
insert into comment_tags
select distinct c.id, ct.tag
from comment c
join comment c2 on c.blogpost_id = c2.blogpost_id
join comment_tags ct on ct.comment_id in (c.id, c2.id)
where not exists (
select 1
from comment_tags ct2
where c.id = ct2.comment_id and ct.tag = ct2.tag);
最后一点意见——出于性能原因,您最好使用左连接/null
而不是不存在
。这在不同的RDBMS之间似乎有所不同:
insert into comment_tags
select distinct c.id, ct.tag
from comment c
join comment c2 on c.blogpost_id = c2.blogpost_id
join comment_tags ct on ct.comment_id in (c.id, c2.id)
left join comment_tags ct2 on c.id = ct2.comment_id and ct.tag = ct2.tag
where ct2.comment_id is null;
从何处获取标记信息?显示完整的sql代码标记已在表中。博客帖子的每条评论都有不同的标签。我们只想将一条评论的每个标签都添加到与给定blog相关联的所有评论中,但我们没有comment_id+标签的主标签。我同意我们应该这样做。但是设计人员忘记了解决这个问题:(@SaqibAli——很公平——我更新了一个不需要主键的解决方案的答案。非常好。谢谢!我明天将在开发环境中试用。再次感谢。