使用连接和分组进行复杂更新
此查询从两个表中选择 ID,其中存在完全一对一的名称匹配
SELECT d.guest_id, h.host_id
FROM `guest` AS g
JOIN `guest_data` AS d
ON d.guest_id = g.guest_id
JOIN host_data AS h
ON d.guest_nm = h.host_nm
GROUP BY
h.venue_nm
HAVING COUNT(*) = 1
现在我在更新 guest
表 (g) 来设置 g.link_id = h.host_id 时遇到问题
基本上我想创建像这样的声明
UPDATE `guest` AS g , `host` h
SET g.link_id = h.host_id
WHERE g.guest_id = ... AND h.host_id = ... the pairs in the previous statement
This query selects ID's from two tables where there are exactly one to one name matches
SELECT d.guest_id, h.host_id
FROM `guest` AS g
JOIN `guest_data` AS d
ON d.guest_id = g.guest_id
JOIN host_data AS h
ON d.guest_nm = h.host_nm
GROUP BY
h.venue_nm
HAVING COUNT(*) = 1
Now I'm having trouble updating guest
table (g) to set the g.link_id = h.host_id
Basically I want to create a statement like
UPDATE `guest` AS g , `host` h
SET g.link_id = h.host_id
WHERE g.guest_id = ... AND h.host_id = ... the pairs in the previous statement
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能遇到的一个问题是,每个来宾可能有许多 host_data 行,因此您必须使用聚合函数(我在下面使用了 max)来获取要从中提取 host_id 的单行。我更喜欢 SQL Server,但我认为这种语法与您将在 MySQL 上使用的语法非常接近。这是我的选择:
在检查选择返回正确的结果集后,您可以轻松地将其转换为 UPDATE 语句:
我希望这足够接近以提供帮助......
A problem you might be having is that you could have many host_data rows for each guest, so you have to use an aggregate function (I used max below) to get to the single row you want to pull a host_id from. I'm more of a SQL Server person, but I think this syntax is pretty close to what you'll use on MySQL. Here's my select:
After checking that the select returns the right result set you can easily convert that into an UPDATE statement:
I hope this is close enough to be of help...
在 Sql Server 中,您可以执行类似
UPDATE guest 的 操作
设置链接 ID = 主机 ID
来自客人 g
...
我从来没有使用过mysql,所以祈祷吧。
In Sql Server, you would do something like
UPDATE guest
SET link_id = host_id
FROM guest g
...
I've never used mysql, so fingers crossed.
稍微查看了一下语法后,我决定分解操作并使用相同的 SELECT 查询来 INSERT INTO 临时表。然后我使用典型的 JOIN 语法执行 UPDATE。
这样做的另一个好处是能够在推送到表之前验证查询结果。
After looking at the syntax for this a bit, I decided to break up the operations and used the same SELECT query to INSERT INTO a temporary table. Then I performed the UPDATE using typical JOIN syntax.
This has the added benefit of being able to verify the query results before pushing to your table.