用主键替换外键

时间:2016-11-27 19:56:13

标签: mysql sql select join

我想知道当两个列属于同一类型时,如何用主键值替换外来值。

表1:用户module Main where class Coordinate c where createCoordinate :: x -> y -> c x y getFirst :: c x y -> x getSecond :: c x y -> y addCoordinates :: (Num x) => (Num y) => c x y -> c x y -> c x y instance Coordinate (,) where createCoordinate a b = (a,b) getFirst (a,_) = a getSecond (_,b) = b addCoordinates a b = (getFirst a + getFirst b, getSecond a + getSecond b) user_id

表2:关注者user_name user_name

(假设名称是唯一的)

我想创建一个查询来获取与 Table2 相同的内容,但是followed_user_name改变了每个user_nameid改变了follower_user_name }}。我很困惑,因为两者都属于同一类型。

到目前为止我所拥有的:

id

PS:这是我正在使用的数据库,我没有设计它。不确定为什么他们只是没有在关注者表中使用id。

2 个答案:

答案 0 :(得分:1)

您可以followers 加入users两次,一次是用户名,一次是跟随用户名:

SELECT u1.id, u2.id
FROM   followers f
JOIN   users u1 ON u1.user_name = f.user_name
JOIN   users u2 ON u2.user_name = f.followed_user_name

答案 1 :(得分:1)

我发现接受的答案有点奇怪:有两个同名属性的结果?!不用说这样的结果是非关系的。

如果您接受我们需要使用rename关系运算符(在SQL中称为AS),那么我们可以将操作推送到表表达式,这将允许使用{{1}这让我们的关系人们感到高兴:

NATRUAL JOIN
相关问题