我试图在一个查询中从两个相关表中获取数据。 表格如下:
表1:
--------------------------
| ID | username |
--------------------------
| 1 | user1 |
| 2 | user2 |
| 3 | user3 |
| 4 | user4 |
--------------------------
表2:
----------------------------------------------------
| ID | user_id | key | value |
----------------------------------------------------
| 1 | 1 | key1 | value1 |
| 2 | 1 | key2 | value2 |
| 3 | 2 | key2 | value3 |
| 4 | 3 | key3 | value4 |
| 5 | 4 | key1 | value5 |
| 6 | 4 | key3 | value5 |
----------------------------------------------------
我想得到一个结果,包括表1中的所有行和表2中key = key1的键值对。如果表1中的密钥不存在于表1中的给定行,请用NULL填充它。预期结果示例:
----------------------------------------------------
| user_id | username | key | value |
----------------------------------------------------
| 1 | user1 | key1 | value1 |
| 2 | user2 | NULL | NULL |
| 3 | user3 | NULL | NULL |
| 4 | user4 | key1 | value5 |
----------------------------------------------------
或者 - 表1中的所有行都不包含表2中key = key1的键值对。
我尝试了来自表2的2个表和SELECT
的标准SELECT
和表2中的JOIN
,但我得到的是表1中包含键值对的所有行表2中的key = key1,这与我想要的完全相反。
有什么建议吗?
答案 0 :(得分:8)
select
t1.id,
t1.username,
t2.key,
t2.value
from
table1 t1
left join table2 t2
on t1.id = t2.user_id
and t2.key = 'key1'
为了获得所有不具备的“替代”,只需添加一个where子句..
where t2.user_id IS NULL
答案 1 :(得分:1)
试试这个:
SELECT t1.username,t2.user_id,t2.key,t2.value FROM table1 as t1 left join table2 as t2 on(t1.id = t2.user_id) and t2.key = 'key'
答案 2 :(得分:-1)
查询可能如下所示:
SELECT t1.username, t2.key, t2.value FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON t1.id = t2.user_id;
例如,如果table2中没有user_id 3,那么查询(上面)将产生:
+----------+------+--------+
| username | key | value |
+----------+------+--------+
| user1 | key1 | value1 |
| user1 | key2 | value2 |
| user2 | key2 | value3 |
| user3 | NULL | NULL |
| user4 | key1 | value5 |
| user4 | key3 | value5 |
+----------+------+--------+