crist
V2EX  ›  问与答

mysql 如何查询一条记录里面的两个相同属性的值呢?

  •  
  •   crist · Jul 30, 2016 · 6366 views
    This topic created in 3748 days ago, the information mentioned may be changed or developed.
    如:
    relation 表里有字段: id 、 uid 、 hid 、 relation
    user 表里有字段: ID 、 name
    uid 和 hid 是对应 user 表里的 ID 的, relation 字段指明两个人的关系。
    现在我要联合查出一条关系记录,并且带有 uid 和 hid 的 name ,用一条语句如何查??求大神指点,谢谢~
    8 replies  •  2016-07-30 11:39:38 +08:00
    skydiver
    skydiver
    Jul 30, 2016 via Android
    1
    as
    crist
    crist
    OP
    Jul 30, 2016
    2
    @skydiver 什么 as
    phperstar
    phperstar
    Jul 30, 2016
    3
    select a.uid,a.hid,a.name from relation a,user b where b.Id = a.uid and uid = xxx;
    aprikyblue
    aprikyblue
    Jul 30, 2016 via Android
    4
    join
    skydiver
    skydiver
    Jul 30, 2016❤️2
    5
    @crist 同一个语句里可以 join 两次同一个表, as 取个别名就行了。

    select id, uid, hid, ralation, A.name as uname, B.name as hname from relation left join user as A on A.ID = uid left join user as B on B.ID = hid.

    (好像 mysql 的话所有的 as 都可以省略,但是大致就是这个意思)
    crist
    crist
    OP
    Jul 30, 2016
    6
    @phperstar Unknown column 'a.name' in 'field list'
    phperstar
    phperstar
    Jul 30, 2016
    7
    @crist b.name ....这错误一看应该就知道呀,找不到字段名
    crist
    crist
    OP
    Jul 30, 2016
    8
    @skydiver 这个是对的, join 同一个表两次,谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2995 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 10:54 · PVG 18:54 · LAX 02:54 · JFK 05:54
    ♥ Do have faith in what you're doing.