坚持mysql左连接

时间:2013-05-31 09:06:39

标签: mysql stored-procedures

我想问一些问题如下:

有3个表,我想将字段type-id上的值tbl1与表中的id匹配

类型。我希望得到结果,列出每个组ID的所有类型名称。

TB1 
Gid TypeID  Value
1   1   5
1   2   10
2   3   6

TBLTYPE
ID  NAME
1   A
2   B
3   C
4   D
5   E


RESULT that i need  

Type  value
A    5
B   10
C   
D   
E   
A   
B   
C   6
D   
E   

4 个答案:

答案 0 :(得分:3)

尝试此查询

select  
    tmp.name, 
    tmp.gid, 
    a.value 
from 
    (select 
        a.*, 
        b.* 
    from 
        (select 
            distinct gid 
        from 
            tbl1 a
        )a, 
        tbl2 b
    ) tmp 
left join 
    tbl1 a 
on 
    a.typeid=tmp.id and 
    a.gid = tmp.gid 
order by      --OPTIONAL PART
    tmp.gid

修改

派生表tmp是此查询的主表,并通过具有唯一gid和tbl2日期的交叉连接派生,该日期为每个用户提供与每个组相关联。 tmp表与tbl1连接,其中得分表给出了所需的表。 您可以在小提琴中单独运行每个派生表,以了解正常工作。

Fiddle (为了正确理解,每个查询单独提及)

FIDDLE

| NAME | GID |  VALUE |
-----------------------
|    A |   1 |      5 |
|    B |   1 |     10 |
|    C |   1 | (null) |
|    D |   1 | (null) |
|    E |   1 | (null) |
|    A |   2 | (null) |
|    B |   2 | (null) |
|    C |   2 |      6 |
|    D |   2 | (null) |
|    E |   2 | (null) |

答案 1 :(得分:0)

SELECT
TBLTYPE.Name As TYpe
TB1.Value,  
Value,
FROM TB1 
JOIN TBLTYPE on TBLTYPE.Id=TB1.ID
GROUP BY TBLTYPE.Type

答案 2 :(得分:0)

SELECT TBLRESULT.NAME as Type, TB1.Value as value FROM TBLRESULT, TB1 LEFT OUTER JOIN TBLTYPE ON TB1.value = TBLTYPE.ID;

答案 3 :(得分:0)

你可以尝试这个(基本上你需要对每个组进行查询):

SELECT
    t1.NAME as 'Type',
    IFNULL(t2.Value,'') as 'value'
FROM
    TBLTYPE t1
LEFT JOIN t2
    ON t2.TypeID = t1.ID
    AND t2.Gid = 1
UNION ALL
SELECT
    t1.NAME as 'Type',
    IFNULL(t2.Value,'') as 'value'
FROM
    TBLTYPE t1
LEFT JOIN t2
    ON t2.TypeID = t1.ID
    AND t2.Gid = 2