0

我很难根据我的需要组装正确的 sql 语句来列出和排序数据。下面是我需要从中选择数据的两个表的结构。

对于 users 表中的每个用户,我需要从 users_nfo 表中列出 id、name 和 key[a] 和 key[b]。

Table users: 
+----+------+
| id | name |
+----+------+
| 1  | aa   |
| 2  | bb   |
| 3  | cc   |
| 4  | dd   |
| 5  | ee   |
+----+------+

Table users_nfo:
+----+-----+-----+-------+
| id | uid | key | value |
+----+-----+-----+-------+
| 1  | 1   | a   | 22    |
| 2  | 1   | b   | 47    |
| 3  | 2   | a   | 38    |
| 4  | 2   | b   | 16    |
| 5  | 3   | a   | 27    |
| 6  | 3   | b   | 67    |
| 7  | 4   | a   | 75    |
| 8  | 4   | b   | 67    |
| 9  | 5   | a   | 63    |
| 10 | 5   | b   | 67    |
+----+-----+-----+-------+

结果应该与此类似

Array result: 
+----+------+---+---+
| id | name | a | b |
+----+------+---+---+
| 1  | aa   |22 |47 |
| 2  | bb   |38 |16 |
| 3  | cc   |27 |67 |
| 4  | dd   |75 |67 |
| 5  | ee   |63 |67 |
+----+------+---+---+

此外,我需要能够按任何列键排序,例如按 b 排序 asc。

帮助表示赞赏。提前致谢!

4

1 回答 1

2

诀窍是将 users_nfo (sic) 表连接两次,并key在连接条件中包含该列。像这样:

SELECT u.ID, u.name, n1.value, n2.value from USERS u
JOIN users_nfo n1
ON u.id = n1.id AND n1.key = 'a'
JOIN users_nfo n2
ON u.id = n2.id AND n1.key = 'b'
ORDER BY n2.value ASC
于 2012-08-19T18:41:19.480 回答