MySQL 更新记录的第一个实例

编程入门 行业动态 更新时间:2024-10-19 18:37:35
本文介绍了MySQL 更新记录的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试做的是根据 contact_id 更新记录的第一个实例.

What im trying ot do is update the first instance of a record based on contact_id.

我有一个电子邮件地址表和相应的contact_id.每个联系人可能有多个电子邮件地址,因此该表可以包含多个相同 contact_id 的实例.

I have a table of email addresses and corresponding contact_id's. Each contact may have more than one email address so the table can contain more than one instance of the same contact_id.

当我点击每个不同 contact_id 的第一个实例时,我想将相应的 is_primary 字段更新为1".

I want to update the corresponding is_primary field to '1', when I hit the first instance of each distinct contact_id.

只要数据库中的每个人都有一个,我不太关心最终会成为主要电子邮件地址的内容.

I'm not too concerned about what ends up being the primary email address as long as everyone in the database has one.

表格示例:

contact_id | email | is_primary --------------------------------------------- 1001 | john@world |0 1001 | desmond@world |0 1002 | person@life |0 1003 | preson@help |0 1003 | bad@sql |0 1003 | have@searched |0

所以我要找的结果是:

contact_id | email | is_primary --------------------------------------------- 1001 | john@world |1 1001 | desmond@world |0 1002 | person@life |1 1003 | preson@help |1 1003 | bad@sql |0 1003 | have@searched |0

已尝试创建临时表并对其进行处理,但查询更新了所有 is_primary 字段.我知道我在这里遗漏了一些基本的东西,但我的 sql 技能有限.

Have tried creating a temp table and macthcing to that, but query updated all is_primary fields. I know im missing something basic here, but my sql skills are limited.

推荐答案

这种技术在子查询中将表与自身连接起来,但它只匹配一行(基于 contact_id 和 电子邮件匹配.技巧是子查询仅返回使用 MIN 的电子邮件地址之一,理论上是按字母顺序排列的第一个(不可靠,但您说这无关紧要).

This technique joins the table against itself in a subquery, but it only matches one row (based on contact_id and email matching. The trick is that the subquery returns just one of the email addresses using MIN, theoretically the first one alphabetically (not reliable, but you said that didn't matter).

我对此进行了测试,结果很好.

I have tested this with good results.

UPDATE email JOIN (SELECT contact_id, MIN(email) as email FROM email GROUP BY contact_id) as singles USING(contact_id, email) set is_primary=1;

更多推荐

MySQL 更新记录的第一个实例

本文发布于:2023-11-16 14:31:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   实例   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!