我有三个表,其中包含人员、属性和属性的潜在值(value)。我想不出一个查询来显示所有人、每个人的属性及其缺失/空属性。
这是一个示例表...

attributes
+---------------------+
| attribute_name (col)|
+---------------------+
| name                |
+---------------------+
| age                 |
+---------------------+
| gender              |
+---------------------+
| email               |
+---------------------+

people
+-----------+----------+
| person_id | value_id |
+-----------+----------+
| 2         | 7        |
+-----------+----------+
| 2         | 9        |
+-----------+----------+
| 3         | 8        |
+-----------+----------+

values
+---------------+----------------+-------+
| value_id (pk) | attribute_name | value |
+---------------+----------------+-------+
| 7             | age            | 35    |
+---------------+----------------+-------+
| 8             | age            | 28    |
+---------------+----------------+-------+
| 9             | gender         | male  |
+---------------+----------------+-------+

如何连接三个表以显示这样的内容?
+-----------+----------+-----------------+--------+
| person_id | value_id | attribute_name  | value  |
+-----------+----------+-----------------+--------+
| 2         | 7        | age             | 35     |
+-----------+----------+-----------------+--------+
| 2         | 9        | gender          | male   |
+-----------+----------+-----------------+--------+
| 2         | NULL     | name            | NULL   |
+-----------+----------+-----------------+--------+
| 2         | NULL     | email           | NULL   |
+-----------+----------+-----------------+--------+
| 3         | 8        | age             | 28     |
+-----------+----------+-----------------+--------+
| 3         | NULL     | gender          | NULL   |
+-----------+----------+-----------------+--------+
| 3         | NULL     | name            | NULL   |
+-----------+----------+-----------------+--------+
| 3         | NULL     | email           | NULL   |
+-----------+----------+-----------------+--------+

最佳答案

SELECT  a.person_ID,
        MAX(c.value_ID) value_ID,
        b.attribute_name ,
        MAX(c.value) Value
FROM    people a
        CROSS JOIN attributes b
        LEFT JOIN `values` c
            ON  a.value_ID = c.value_ID AND
                b.attribute_name = c.attribute_name
GROUP BY a.person_ID, b.attribute_name
  • SQLFiddle Demo
  • 关于MySQL 查询三个表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14674949/

    10-13 04:31