mysql以不同的ID加入同一张表

时间:2018-11-01 11:48:46

标签: mysql sql join

表:数据表

    +----+-------+-------+
    | Id | Name  | Value |
    +----+-------+-------+
    | 50 | Eric  | 1200  |
    | 50 | Barb  | 1195  |
    | 50 | Joe   | 1180  |
    | 51 | Barb  |   6   |
    | 51 | Eric  |   3   |
    | 51 | Joe   |   5   |
    +----+-------+-------+

我想要这个结果

    +-------+---------+--------+
    | Name  | Value1  | Value2 |
    +-------+---------+--------+
    | Eric  |  1200   |   3    |
    | Barb  |  1195   |   6    |
    | joe   |  1180   |   5    |
    +-------+---------+--------+

我不知道如何合并。

SELECT name, value from datatable WHERE Id=50 AS Value1 
JOIN datatable 
WHERE Id=51 AS  Value2 ON value1.Name = value2.Name ORDER BY value1.Value

不知道该怎么打value2

$row["??"]

2 个答案:

答案 0 :(得分:1)

  • 您可以在Group By上进行Name
  • 现在,您可以使用Case .. WhenMax()函数来利用条件聚合。

尝试以下查询:

SELECT 
  t.Name, 
  MAX(CASE WHEN t.Id = 50 THEN t.VALUE END) AS Value1,
  MAX(CASE WHEN t.Id = 51 THEN t.VALUE END) AS Value2 
FROM datatable AS t
GROUP BY t.Name

答案 1 :(得分:0)

使用表别名

SELECT t1.name, t1.value AS Value1,t2.value AS Value2 from datatable t1 
JOIN datatable t2 ON t1.Name = t2.Name
WHERE t1.Id=51 and t2.Id=50 
ORDER BY value1.Value