这是我的学生记录表,我试图为每个学生找到具有相同名字或姓氏的其他学生的数量,并为每个学生保存在同一个和同一个学生中。
+-----------+-------------+------+-----+---------+-------+
| 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;
上面的查询给了我每个学生和他的第一个或最后一个与另一个学生的匹配,但是我在为每个学生计算时遇到困难并将其插入到同一个和同一个学生中。谢谢你的推荐
答案 0 :(得分:2)
使用相关子查询为每个学生找到具有相似名字或姓氏的学生。
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
答案 1 :(得分:1)
这很复杂,因为您需要进行更新。在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);