1

我有这两张表:

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_numberstudentdates.student_ticket_number字段student_id匹配的位置。

因此,如果用户 John has student_id= 1 将他的票号(例如 1234)从 移动students.student_ticket_numberstudentdates.student_ticket_number WHERE student_id = '1'

在表studentdates.student_id中可以有多个相同的记录,然后我想使用最低的studentdates.student_date_id并跳过其他的。告诉我这是否不清楚。

我想我需要以某种方式进行子查询,但是如何?

4

2 回答 2

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
于 2012-09-26T06:55:01.393 回答
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'
于 2012-09-26T06:55:38.227 回答