我想查询4号人物的朋友的姓名,所以'otherPerson_id'中的数字,但我的尝试只查询'person_id'中的id或名字。我怎么能要求查询关于4号人的朋友的信息,而不是关于4号人本身的信息呢?
这是我的尝试:
$q = "SELECT DISTINCT p.idperson, p.name FROM person p INNER JOIN people_friends pf ON p.idperson = pf.person_id AND p.idperson = 4";
$res = $connexion->query($q);
$res->setFetchMode(PDO::FETCH_COLUMN);
while($record = $res->fetch()) {
echo $record[name];
echo "<br/>";
}
表:(所以当我寻找4号人的朋友时,我希望它返回1和7)
编辑:
CREATE TABLE people_friends
(
person_id integer NOT NULL,
otherperson_id integer NOT NULL,
CONSTRAINT people_friends_pkey PRIMARY KEY (person_id, otherperson_id),
CONSTRAINT people_friends_person_id_fkey FOREIGN KEY (person_id)
REFERENCES person (idperson) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT people_friends_person_id_fkey1 FOREIGN KEY (person_id)
REFERENCES person (idperson) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
CREATE TABLE person
(
idperson integer NOT NULL,
name character varying(50),
map bytea,
CONSTRAINT person_pkey PRIMARY KEY (idperson)
)
由于
答案 0 :(得分:2)
尝试此查询。
SELECT DISTINCT
pFriend.idperson, pFriend.name
FROM people_friends pf
INNER JOIN person pFriend on pf.otherperson_id = pFriend.idperson
WHERE
pf.person_id = 4
答案 1 :(得分:0)
您只需添加一个WHERE子句来检查pf表。
SELECT DISTINCT p.idperson
,p.name
FROM person p
INNER JOIN people_friends pf
ON p.idperson = pf.person_id
WHERE pf.otherperson_id = 4