gpt4 book ai didi

MySQL查询三张表省略列中重复项

转载 作者:行者123 更新时间:2023-11-30 23:28:45 24 4
gpt4 key购买 nike

有 3 个表:pers、skills、articles(人有 n 项技能并写了 n 篇文章)

(T1) 人

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 关系,连续连接不会这样做 -> 不是 T1 x T2 x T3,而是 (T1 x T2) x (T1 x T3) 根据 this question .

我试过:

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”也不希望出现两次。

感谢任何建议!

最佳答案

为每个人的每篇文章和每个人的每项技能分配一个行号。

所以现在你的数据会像

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

现在Full Outer Join技巧和关于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

现在与 person 一起加入以获得所需的结果。

这个 SO 问题解释了如何在选择中分配等级/行号。 MySQL - Get row number on select

关于MySQL查询三张表省略列中重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11778385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com