得到3个表:人,技能,文章(人具有 n 技能并撰写 n 文章)
(T1)pers
1 John
2 Joe
(T2)技能
1 John_sings
1 John_laughs
2 Joe_runs
(T3)文章
1 John_article_1
2 Joe_article_1
3 Joe_article_2
我期待:
John - John_laughs - John_article_1
John - John_sings - [NULL]
Joe - Joe_runs - Joe_article_1
Joe - [NULL] - Joe_article_2
因为我们有2个独立的1:n关系,连续的连接不会这样做 - >根据{{3}},不是T1 x T2 x T3,而是(T1 x T2)x(T1 x T3)。
我试过了:
SELECT child1.id,
child1.name,
child1.skill,
child2.title
FROM
(SELECT pers.id,
pers.name,
skills.skill
FROM pers
LEFT JOIN skills ON pers.id = skills.pers_id) child1
INNER JOIN
(SELECT pers.id,
article.title
FROM pers
LEFT JOIN article ON pers.id = article.pers_id) child2 ON child1.id = child2.id
但显示
John - John_laughs - John_article_1
John - John_sings - John_article_1
Joe - Joe_runs - Joe_article_1
Joe - Joe_runs - Joe_article_2
显然,我不想两次“Joe_runs”,两次都不想要“John_article_1”。
感谢任何建议!
答案 0 :(得分:0)
为每个人和每个人的每项技能分配行号。
所以现在你的数据就像
T1) pers
PId Name
1 John
2 Joe
(T2) skills
PId Skill Rank
1 John_sings 1
1 John_laughs 2
2 Joe_runs 1
(T3) article
PId Article Rank
1 John_article_1 1
2 Joe_article_1 1
2 Joe_article_2 2
现在全面的外部加入技巧和关于Pid和Rank的文章,它应该给你
PID Skill Article
1 John_Sings john_Article_1
1 John_Laughs Null
2 Joe_runs Joe_article_1
2 Null Joe_Article_2
现在与人联系以获得所需的结果。
这个SO问题解释了如何在选择中分配rank / rownumber。 MySQL - Get row number on select
答案 1 :(得分:0)
您想要的结果是典型的LEFT JOIN。你应该这样做:
SELECT * FROM T1
LEFT JOIN T2 on (T1.id=T2.id)
LEFT JOIN T3 on (T1.id=T3.id);
这与2个独立的1:n关系兼容,请注意,这加入了T1-T2和T1-T3