如何使用JOIN

时间:2016-03-31 06:44:43

标签: mysql sql

我有两张桌子,即学生和通行证。在两个表中,一列是常见的,即ID。我需要学生数据,包括仅在一个水平行中的传递表详细信息,现在它显示在三个不同的行中。学生数据不断变得多余。

ID   Name Age
1     XYZ    25
2     ABC    15

ID    subject      External  Internal
1       English       20       22
1       Maths         25       15
1       Science       50       25
2       history       15       14
2       Geography     14       21

预期产出:

ID   NAME   AGE                         Pass 
1    XYZ    25      English       20       22  Maths         25       15  Science       50       25
2    ABC    15      history       15       14  Geography     14       21

实际输出:

ID  NAME  AGE  SUBJECT      EXTERNAL INTERNAL
1   XYZ    25   English        20       22
1   XYZ    25    Maths         25       15
1   XYZ    25    Science       50       25

SQL QUERY:

SELECT * FROM students LEFT JOIN pass ON students.ID=pass.ID order by students.ID

是否可以在一个水平行中显示?我试过加入,但我认为它不起作用。

4 个答案:

答案 0 :(得分:0)

试试这个,但你有1列的结果。

SELECT
  s.*,
  GROUP_CONCAT(CONCAT(p.subject,' : ',p.External,' : ',p.Internal) SEPARATOR '  --  ')
FROM students s
LEFT JOIN pass p ON s.ID=p.ID
GROUP BY p.ID
ORDER BY s.ID;

答案 1 :(得分:0)

一个丑陋的解决方案:

SELECT ID,NAME,
group_concat(concat(SUBJECT,"==ex=>",EXTERNAL,"==IN=>",INTERNAL,"==|"), SEPARATOR "--|") 
FROM students LEFT JOIN pass ON students.ID=pass.ID 
group by ID,NAME order by students.ID

答案 2 :(得分:0)

试一试 -

{{1}}

答案 3 :(得分:0)

您可以使用动态旋转来解决您的问题。一种方法可能是使用这些陈述:

SELECT      GROUP_CONCAT(tmp.x)
    FROM    (
        SELECT      CONCAT('MAX(IF(p.subject = ''', p.subject, ''', p.External, NULL)) ', p.subject, '_External, MAX(IF(p.subject = ''', p.subject, ''', p.Internal, NULL)) ', p.subject, '_Internal') x
            FROM    pass p
        GROUP BY    p.subject
        ) tmp
    INTO    @query;

SELECT      CONCAT('SELECT s.*, ', @query, ' FROM students s JOIN pass p ON p.ID = s.ID GROUP BY p.ID')
    INTO    @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;