我有成员表
table members :
pid| id | name
1 | id01 | jenny
2 | id02 | kain
3 | id03 | alex
并有另一个表members_opt
table members_opt
pid | members_id | category
1 | id01 | cat
2 | id01 | dog
3 | id02 | dog
4 | id03 | NULL
现在我使用下面的SQL查询
SELECT * FROM members a JOIN
(SELECT members_id, max(category) as category FROM members_opt GROUP BY members_id) b
ON a.id = b.members_id
但是这个SQL Query没有捕获“id03”的数据,因为“id03”的members_opt.category是NULL
我想要这个结果
result :
id | name | category
id01 | jenny | cat
id02 | kain | dog
id03 | alex | NULL
(结果现在显示双重名称,双重id值。)
我如何使用SQL查询?
答案 0 :(得分:0)
你可以试试这个 -
SELECT * FROM成员JOIN (SELECT members_id,max(类别为IS NULL,然后为0)作为类别FROM members_opt GROUP BY members_id)b ON a.id = b.members_id
答案 1 :(得分:0)
使用以下查询获得所需的输出 -
SELECT a.id, a.name, b.category FROM members a INNER JOIN
(SELECT members_id, category FROM members_opt GROUP BY members_id) b
ON a.id = b.members_id
答案 2 :(得分:0)
只需将JOIN
更改为LEFT JOIN
:
SELECT a.id, a.name, b.category
FROM members a
LEFT JOIN (
SELECT members_id, max(category) as category
FROM members_opt GROUP BY members_id) b
ON a.id = b.members_id
如果你想'cat'代表'jenny',你应该使用聚合函数min
。