我们有两个表(comment和comment_tags)如下:
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 | |
+------------+-------------+------+-----+---------+-------+
每个评论都可以有不同的标签。现在我们要将所有评论标签传播到同一博客帖子的所有评论。所以基本上我们想要使每个blogpost上的所有评论的所有comment_tags都相同。
我知道我们可以编写脚本或PL / SQL来执行此操作。但我想知道是否有一个mySQL查询可以做到这一点。
是否可以使用单个mySQL查询将评论中的所有标记传播到同一篇博文的所有评论中?
答案 0 :(得分:2)
假设您的primary key
表格中有comment_id
和tag
字段的复合comment_tags
(听起来应该是这样),那么您可以使用{{ 1}}:
insert ignore
修改强> 的
根据您的意见,您可以在查询中添加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)
:
not exists
最终评论 - 出于性能原因,您最好使用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);
vs left join/null
。这似乎在不同的RDBMS之间有所不同:
not exists