mysql将一列值替换为另一列

时间:2012-10-14 19:25:26

标签: mysql

我正在尝试从mysql数据库中提取学生和他们注册的课程。我想用输出中的课程名称替换课程ID。

我有这些表格和列:

表:users_to_courses 列:users_LOGINcourses_ID

表:users 列:loginnamesurname

表:courses 列:idname

这些表格如下:

users_to_courses.users_LOGIN = users.login 
users_to_courses.courses_ID = courses.id

我正在尝试输出姓氏,姓名,课程(按名称而不是id),因此它看起来像史密斯,约翰化学,物理,作文

以下是我尝试失败的原因:

SELECT
users.surname,
users.name,
users.login,
users_to_courses.users_LOGIN,
(select group_concat (courses.name) from courses
where users_to_courses.users_LOGIN = users.login and users_to_courses.courses_ID =    
courses.id
GROUP BY users.surname) as courses
from courses join users_to_courses
on courses.id = users_to_courses.courses_ID

3 个答案:

答案 0 :(得分:1)

SELECT users.login, users.surname, users.name, courses.name
FROM users_to_courses
INNER JOIN users ON users_to_courses.users_LOGIN = users.login
INNER JOIN courses ON users_to_courses.courses_ID = courses.id
GROUP BY users_to_courses.users_LOGIN

目前还不完全清楚users_to_courses表是如何组织的,如果它是每行一个类,那么每个类最终会有一行,但是对应于同一个用户ID的所有行都将在表...

如果users_to_courses.courses_ID条目是多个课程ID的列表,则可能无效......

答案 1 :(得分:0)

 SELECT users.surname, users.name, users.login, users_to_courses.users_LOGIN from courses c 
 INNER JOIN users_to_courses uc ON  uc.courses_ID = c.id
 INNER JOIN login l ON uc.users_login = l.login

答案 2 :(得分:0)

试试这个

Select

    u.surname,
    u.name,
    u.login,
    uc.users_LOGIN,
    c.Name,

    --added this line
    group_concat (c.name)  
From users_to_courses uc
JOIN users u ON uc.users_LOGIN = u.login 
JOIN courses c ON uc.courses_ID = c.id

-- added this line
GROUP BY u.surname, u.name, u.login, uc.users_LOGIN