SQL联合选择多个列

时间:2014-10-15 15:10:23

标签: mysql sql

我试图从两个相同的表中选择得分和user_id(从表名中删除)

SELECT user_id, score as score
    FROM (
        SELECT tes.score FROM test_score tes INNER JOIN user U ON U.id = tes.user_id WHERE U.organization_id = 7
        UNION ALL
        SELECT tas.score FROM task_score tas INNER JOIN user U ON U.id = tas.user_id WHERE U.organization_id = 7
    ) AS subquery ORDER BY score DESC LIMIT 10

然而,当我运行这个时,我得到以下错误:

Error Code: 1054. Unknown column 'user_id' in 'field list'

表格如下:

Table: test_score
Columns:
id  int(11) PK AI
user_id int(11) 
module_id   int(11) 
score   double 
number_correct  int(11) 
correct_total   int(11) 
timestamp   datetime 
phase_id    int(11) 
medal_id    int(11) 
team_id int(11) 
status_id   int(11) 

2 个答案:

答案 0 :(得分:1)

您的内部查询不会返回任何名为user_id的列,因此外部查询无法访问它。

请改为尝试:

SELECT user_id, score as score
    FROM (
        SELECT tes.user_id, tes.score FROM test_score tes INNER JOIN user U ON U.id = tes.user_id WHERE U.organization_id = 7
        UNION ALL
        SELECT tas.user_id, tas.score FROM task_score tas INNER JOIN user U ON U.id = tas.user_id WHERE U.organization_id = 7
    ) AS subquery ORDER BY score DESC LIMIT 10

答案 1 :(得分:0)

您需要在两个SELECT语句中的子查询中选择user_id。

SELECT user_id, score as score
    FROM (
        SELECT tes.user_id, tes.score FROM test_score tes INNER JOIN user U ON U.id = tes.user_id WHERE U.organization_id = 7
        UNION ALL
        SELECT tas.user_id, tas.score FROM task_score tas INNER JOIN user U ON U.id = tas.user_id WHERE U.organization_id = 7
    ) AS subquery ORDER BY score DESC LIMIT 10