get-real-column与sql

o7jaxewo  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(465)

我想知道如何才能在我的请求返回一个真正的列(代码)。
我总是从peoples表中得到相同的代码,而不是真正的代码:它是父代码而不是子代码。
目前我有4张table:

| Peoples (id, code) <- this code
| PeopleFriends (id, fk_user_id, fk_friend_id)
| PeopleTranslations (id, user_name, fk_people_id, fk_language_id)
| Languages (id, code)

有了这些数据:

Peoples:
[id: 1, code: HUMAN1]
[id: 2, code: HUMAN2]
[id: 3, code: HUMAN3]
[id: 4, code: HUMAN4]
[id: 5, code: HUMAN5]

PeopleFriends:
[id: 1, fk_user_id: 1, fk_friend_id: 2]
[id: 2, fk_user_id: 1, fk_friend_id: 3]
[id: 3, fk_user_id: 1, fk_friend_id: 4]
[id: 4, fk_user_id: 1, fk_friend_id: 5]

PeopleTranslations:
[id: 1, username: "username human 1", fk_people_id: 1, fk_language_id: 1]
[id: 2, username: "username human 2", fk_people_id: 2, fk_language_id: 1]
[id: 3, username: "username human 3", fk_people_id: 3, fk_language_id: 1]
[id: 4, username: "username human 4", fk_people_id: 4, fk_language_id: 1]
[id: 5, username: "username human 5", fk_people_id: 5, fk_language_id: 1]

Languages:
[id: 1, code: "EN"]

如果我执行此请求:

SELECT pt.fk_people_id AS id, p.code, pt.user_name FROM Peoples p 
INNER JOIN PeopleFriends pf ON p.id = pf.fk_user_id 
INNER JOIN PeopleTranslations pt ON pf.fk_friend_id = pt.fk_people_id 
INNER JOIN Languages l ON pt.fk_language_id = l.id 
WHERE l.code = 'EN'
AND p.id = 1

我有一个结果:

[
TextRow {
    id: 2,
    code: 'HUMAN1', <--- I would like HUMAN2, not parent code
    user_name: 'username human 2',
},
TextRow {
    id: 3,
    code: 'HUMAN1', <--- I would like HUMAN3, not parent code
    user_name: 'username human 3',
},
TextRow {
    id: 4,
    code: 'HUMAN1', <--- I would like HUMAN4, not parent code
    user_name: 'username human 4',
},
TextRow {
    id: 5,
    code: 'HUMAN1', <--- I would like HUMAN5, not parent code
    user_name: 'username human 5',
}
]
...

我总是使用相同的代码“human1”,而不是真正的代码“human2”、“human3”、“human4”
是p.id=1的代码。。。
我试图添加p代码,但我有相同的错误。

ercv8c1e

ercv8c1e1#

SELECT pt.fk_people_id AS id, 
       p1.code, 
       pt.user_name 
FROM       Peoples p 
INNER JOIN PeopleFriends pf      ON p.id = pf.fk_user_id 
INNER JOIN Peoples p1            ON p1.id = pf.fk_friend_id
INNER JOIN PeopleTranslations pt ON pf.fk_friend_id = pt.fk_people_id 
INNER JOIN Languages l           ON pt.fk_language_id = l.id 
WHERE l.code = 'EN'
  AND p.id = 1

将查询简化为

SELECT pt.fk_people_id AS id, 
       p1.code, 
       pt.user_name 
FROM       PeopleFriends pf
INNER JOIN Peoples p1            ON p1.id = pf.fk_friend_id
INNER JOIN PeopleTranslations pt ON pf.fk_friend_id = pt.fk_people_id 
INNER JOIN Languages l           ON pt.fk_language_id = l.id 
WHERE l.code = 'EN'
  AND pf.fk_user_id = 1

相关问题