0

下面是我使用 SQL 为数据库创建的表。我不知道如何从 likes 表中获取 ID 和 LIKED 显示的名称。

这个作业应该很简单,能够显示喜欢对方的人的名字。有一个数据输入表单,要求为彼此喜欢的人输入 ID,但是我必须显示两个互相喜欢的人的名字......我希望我没有让这个混淆. 是否有可能某些 SQL 代码显示谁喜欢谁的名字。

CREATE TABLE person 
(
    ID INT PRIMARY KEY,
    NAME VARCHAR(50)
) engine=innodb;

CREATE TABLE likes 
(
    ID INT,
    LIKED INT,
    constraint likesPK primary key(ID,LIKED),
    constraint personFK foreign key(ID) references person(ID)
    on delete cascade on update cascade,
    constraint nameFK foreign key(LIKED) references person(ID)
    on delete cascade on update cascade
) engine=innodb;

我尝试做但需要多一列来显示“喜欢”的人的示例:

     select B.id, B.name, A.lIKED from likes A, person B where A.id=B.id AND A.id = 1;
4

3 回答 3

3

首先,我朝你的大致方向挥动手指。编程需要精确,而您的短语“使用 sql”含糊不清。如果你的意思是 sql server 就这么说吧。事实上,编辑您的帖子并添加适当的标签。

其次,您的 on delete 级联位于错误的位置。事实上,在这种情况下,删除级联可能是一个非常糟糕的主意。

第三,那又是什么?哦,是的,你的问题。如何向彼此喜欢的人展示?大概是这样的:

select p1.whatever, p2.whatever
from person p1  -- this would be me
join likes l1 on p1.id = l1.id  -- this is who I like, which is you
join likes l2 on l1.liked = l2.id -- this is who you like, which is me
join person p2 on l2.id = p2.id  -- this is you
etc

顺便说一句,我不认为这很简单。

于 2013-04-27T03:52:09.507 回答
0

尝试这个

select b.id, b.name, (select name from person where id = a.liked) 
from likes a join person b 
on a.id = b.id
where b.id = some id AND b.id = a.id
于 2013-04-27T03:50:09.367 回答
0

似乎您的like表格应该有两个对该person表格的引用(使其成为中间/数据透视表);基本上,一个“like-ee”和一个“like-or”。所以like应该看起来像这样:

like
--------------
ID int
PersonWhoLikedID int
PersonWhoWasLikedID int

然后你的查询变成这样:

SELECT B.name, C.name AS `Liked Person`
FROM likes
LEFT JOIN person B ON likes.PersonWhoLikedID = B.ID
LEFT JOIN person C ON likes.PersonWhoWasLikedID = C.ID
于 2013-04-27T03:50:25.633 回答