MySQL内连接在不同命名的列上

时间:2014-10-24 22:13:22

标签: mysql join

我正在尝试在网站上建立朋友列表功能,我正在创建纯粹为了自己的教育而学习PHP。我有一个名为friends的表,它的列名为id1id2status1status2 - 添加了朋友的人的ID位于id1列中,而添加人员的ID位于id2列中。对于status1,它保存值0或1 - 默认情况下设置为1,添加好友时 - 对于status2,默认情况下设置为0并设置为{ {1}}当添加的人确认好友请求时。

现在,我需要做的是加入两个表,以便我可以确定添加的人的用户名和发出请求的人。 1id1与另一个名为id2的表中的id列相关。

现在我相信我需要在user_infofriends上进行内部联接,但是我只知道当列共享相同名称时如何做到这一点。如何在两个不同命名的列上进行内连接?

2 个答案:

答案 0 :(得分:2)

也许有点偏离主题,但我想通过建议其他架构回答你的问题。

检查出来; http://sqlfiddle.com/#!2/7dde0/4

create table users (
  id int,
  name varchar(255)
);

create table friendships (
  user1 int,
  user2 int
);

create table friend_requests (
  user1 int,
  user2 int
);

# We have 3 users
insert into users values(1, 'John'), (2, 'Alice'), (3, 'Tom');

# John and Alice are friends
insert into friendships values(1, 2);

# Alice and Tom are friends
insert into friendships values(2, 3);

# John send Tom a friend request
insert into friend_requests values(1, 3);

# John's friends
select id, name from users
inner join friendships
on user2 = id and user1 = 1
or user1 = id and user2 = 1;

# Tom's friend requests
select id, name from users
inner join friend_requests on id = user1
where user2 = 3;

# Alice's friends
select id, name from users
inner join friendships
on user2 = id and user1 = 2
or user1 = id and user2 = 2;

答案 1 :(得分:0)

这已经过测试,似乎有效。

使用此user_info表:

enter image description here

有了这个朋友表:

enter image description here

运行此查询:

select ui1.name as initiator, ui2.name as responder
from pl2.friends f
left join pl2.user_info ui1 on f.id1 = ui1.id
left join pl2.user_info ui2 on f.id2 = ui2.id

你得到:

enter image description here