这是我的学生记录表,我试图为每个学生找出同名或同姓的其他学生的数量,并把它放在第一位,为每个学生保存。
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| first | varchar(20) | YES | | NULL | |
| last | varchar(25) | YES | | NULL | |
| samefirst | int(11) | YES | | NULL | |
| samelast | int(11) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
select a.first as af, a.last as al, b.first as bf, b.last as bl
from StudRec a inner join
StudRec b
on a.first = b.first and a.last <> b.last) or
a.first <> b.first and a.last = b.last;上面的查询提供给我每个学生和他的第一个或最后一个学生匹配,但是我在为每个学生做计数并将其插入samefirst和samelast时遇到了困难。先谢
发布于 2015-12-26 18:19:23
使用关联子查询查找每个学生的名字或姓氏相似的学生。
SELECT SR.first,
SR.last,
(SELECT COUNT(*) FROM StudRec AS SR2
WHERE SR2.first = SR.first) AS samefirst,
(SELECT COUNT(*) FROM StudRec AS SR2
WHERE SR2.last = SR.last) AS samelast
FROM StudRec AS SR发布于 2015-12-26 18:17:24
这很复杂,因为您需要进行更新。在MySQL中,不应该使用子查询中正在更新的表。您可以使用join来解决这个问题。
update studrec sr left join
(select first, count(*) as cnt
from studrec
group by first
) f
on sr.first = f.first left join
(select last, count(*) as cnt
from studrec
group by last
) l
on sr.last = l.last
set samefirst = coalesce(f.cnt, 0),
samelast = coalesce(l.cnt, 0);https://stackoverflow.com/questions/34473896
复制相似问题