我有这两个表:
desc students
+-----------------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+---------+------+-----+---------+----------------+
| student_id | int(11) | NO | PRI | NULL | auto_increment |
| student_ticket_number | int(11) | YES | | 0 | |
+-----------------------+---------+------+-----+---------+----------------+
desc studentdates
+-----------------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+---------+------+-----+---------+----------------+
| student_date_id | int(11) | NO | PRI | NULL | auto_increment |
| student_id | int(11) | YES | | NULL | |
| student_ticket_number | int(11) | YES | | 0 | |
+-----------------------+---------+------+-----+---------+----------------+
我想将列students.student_ticket_number
移至studentdates.student_ticket_number
,其中字段student_id
匹配。
因此,如果用户John student_id
= 1,则将其票号(例如1234)从students.student_ticket_number
移至studentdates.student_ticket_number WHERE student_id = '1'
。
在表studentdates.student_id
中,可以有多个相同的记录,然后我想使用最低studentdates.student_date_id
并跳过其他记录。如果不清楚,请告诉我。
我想我需要以某种方式做一个子查询,但是怎么做?
答案 0 :(得分:1)
Update studentdates sd,students s,(select student_id,min(student_date_id) as minstudDateId from studentdates group by student_id) sm
SET sd.student_ticket_number = s.student_ticket_number
where sd.student_id=s.student_id
and sd.student_id=sm.student_id
and sd.student_date_id=sm.minstudDateId
答案 1 :(得分:1)
您需要在子查询中获得最小student_date_ID
,然后将其与其他表连接。试试这个,
<击> 撞击>
<击>UPDATE students a
INNER JOIN studentdates b
ON a.student_ID = b.student_ID
INNER JOIN
(
SELECT student_ID, MIN(student_date_ID) minID
FROM studentDates
GROUP BY student_ID
) c ON b.student_ID = c.student_ID AND
b.student_date_id = c.minID
SET a.student_ticket_number = b.student_ticket_number
WHERE a.student_id = '1'
击> <击> 撞击>
UPDATE students a
INNER JOIN studentdates b
ON a.student_ID = b.student_ID
INNER JOIN
(
SELECT student_ID, MIN(student_date_ID) minID
FROM studentDates
GROUP BY student_ID
) c ON b.student_ID = c.student_ID AND
b.student_date_id = c.minID
SET b.student_ticket_number = a.student_ticket_number
WHERE a.student_id = '1'