有没有办法合并只有最后 personal_id's ,其中我的列中有值?
让我们说安德森和p_id 2结婚了,他的名字改变了。
id p_id last_name job Hobby
1 1 Smith Programmer NULL
2 2 Anderson Influencer Reading
3 2 McKing Influencer NULL
4 3 Jordan Mother Cooking
5 1 Smith NULL Soccer
例如我得到:
p_id:1 - 史密斯 - 程序员 - 足球
p_id:2 - 麦金 - 影响者 - 阅读
提前致谢。
更新
你们真的很严格。
我尝试了几个问题但我无法达到目标。
SELECT * FROM表GROUP_BY p_id ORDER_BY id ASC
答案 0 :(得分:1)
SELECT t.last_name, t.job, t.hobby
FROM {THE_TABLE) as t
JOIN {THE_TABLE} as t2 on t2.p_id = t.p_id
WHERE t.job is not null
AND t.hobby is not null
答案 1 :(得分:1)
CREATE TABLE QUEST (
id INT NOT NULL,
p_id INT NOT NULL,
last_name VARCHAR(50) NOT NULL,
job VARCHAR(50),
hobby VARCHAR(50));
INSERT INTO quest VALUES (1,1,'Smith','Programmer',NULL );
INSERT INTO quest VALUES (2,2,'Anderson','Influencer','Reading' );
INSERT INTO quest VALUES (3,2,'McKing','Influencer', NULL );
INSERT INTO quest VALUES (4,3,'Jordan','Mother','Cooking' );
INSERT INTO quest VALUES (5,1,'Smith',NULL,'Soccer' );
INSERT INTO quest VALUES (6,3,'Jordan','Mother','Cooking' );
INSERT INTO quest VALUES (7,4,'John',NULL,NULL );
INSERT INTO quest VALUES (8,5,'Mike','Test',NULL );
INSERT INTO quest VALUES (9,5,'Mick','Tester',NULL );
COMMIT;
SELECT q.p_id,
q.last_name,
(SELECT job FROM Quest WHERE job IS NOT NULL AND p_id = q.p_id ORDER BY id DESC LIMIT 1) job,
(SELECT hobby FROM Quest WHERE hobby IS NOT NULL AND p_id = q.p_id ORDER BY id DESC LIMIT 1) hobby
FROM Quest q
WHERE id IN (SELECT MAX(id) FROM Quest GROUP BY P_Id )
ORDER BY p_id;
Result:
p_id - last_name - job - hobby
1 - Smith - Programmer - Soccer
2 - McKing - Influencer - Reading
3 - Jordan - Mother - Cooking
4 - John - NULL - NULL
5 - Mick - Tester - NULL