将MySQL Query连接到每个用户的单行

时间:2017-04-17 23:28:35

标签: mysql distinct-values

我有一个查询,我试图将另一个表中的每个用户的值转换为结果中的一个输出行。

SELECT DISTINCT table1.ID, table1.username, table1.display_name,
                 CASE WHEN table2.meta_key = 'vgm' THEN table2.meta_value END VGM,
                 CASE WHEN table2.meta_key = 'year_completed' THEN table2.meta_value END 'Year Completed',
                 CASE WHEN table2.meta_key = 'status' THEN table2.meta_value END Status,
                 CASE WHEN table2.meta_key = 'military_grade' THEN table2.meta_value END 'Military Grade'
          FROM   table1, table2
          WHERE  table1.ID = table2.user_id

我最终得到的结果如下。如果可能的话,我希望将所有用户信息放在一行中。有人有什么建议吗?感谢。

<table>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
<td>NULL</td>
<td>NULL</td>
<td>Baja</td>
<td>NULL</td>
</tr>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
<td>NULL</td>
<td>112</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>Subt</td>
</tr>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
<td>No</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</table>

表1如下:

<table>
<tr>
<td>ID</td>
<td>NAME</td>
<td>EMAIL</td>
</tr>
<tr>
<td>3</td>
<td>user1</td>
<td>Username Last</td>
</tr>
<tr>
<td>4</td>
<td>user2</td>
<td>Username2 Last2</td>
</tr>
</table>

表2如下:

<table>
<tr>
<td>ID</td>
<td>USER_ID</td>
<td>META_KEY</td>
<td>META_VALUE</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>Key 1</td>
<td>Value 1</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>Key 2</td>
<td>Value 2</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>Key 1</td>
<td>Value 1</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>Key 2</td>
<td>Value 2</td>
</tr>
</table>

1 个答案:

答案 0 :(得分:0)

下面的查询与您的查询之间的主要区别在于我采用table2并为每个meta_key创建子查询,然后使用table1将这些子查询加入LEFT JOIN。这应该会为每个用户生成一条记录。

您的表架构和查询存在一些不一致,例如table1user_namedisplay_name,但架构有NAMEEMAIL。我继续使用你的查询字段名称。

SQL查询

SELECT
    users.ID AS Id,
    users.username AS UserName,
    users.display_name AS DisplayName,
    vgm.meta_value AS VGM,
    year_completed.meta_value AS YearCompleted,
    status.meta_value AS Status,
    military_grade.meta_value AS MilitaryGrade

-- Users --
FROM table1 AS users

-- VGM --
LEFT JOIN (
    SELECT user_id, meta_key, meta_value 
    FROM table2 
    WHERE meta_key = 'vgm') 
AS vgm ON users.ID = vgm.user_id

-- Year Completed --
LEFT JOIN (
    SELECT user_id, meta_key, meta_value 
    FROM table2 
    WHERE meta_key = 'year_completed') 
AS year_completed ON users.ID = year_completed.user_id

-- Status --
LEFT JOIN (
    SELECT user_id, meta_key, meta_value 
    FROM table2 
    WHERE meta_key = 'status') 
AS status ON users.ID = status.user_id

-- Military Grade --
LEFT JOIN (
    SELECT user_id, meta_key, meta_value 
    FROM table2 
    WHERE meta_key = 'military_grade') 
AS military_grade ON users.ID = status.user_id