MySQL一条语句同时关联另一个表的两个字段

现在遇到了个,在设计一个mysql文章评论部分时,遇到一个MySQL的语句不会写。先看表:

图片描述

最后想要的结果是: 张三 回复 李四:文章很好
根据我的经验,用MySQL的where方法只能获得comment表中uid或者to_uid在user中的姓名,比如:

select * from user u, comment c where u.uid = c.uid

上面语句的出来的是评论表中评论者(张三)在用户表的name值,李四的name值没能到,有什么办法可以同时得到张三和李四的name值的呢,谢谢大家指点一下!

阅读 5.7k
4 个回答
select * from user u, user tu, comment c where u.uid = c.uid and tu.uid = c.to_uid

试试?

alter table comment add index UID(uid);
alter table comment add index TOUID(to_uid);

如果是单一的评论级记录,建议的sql为:
re1 = select uid, to_uid, `content` from comment where id = xx;
select name from user where uid in (re1.uid, re1.to_uid);
拼接最终结果
或
3楼答案亦可

如果是多记录的方式,这里以查找uid用户为条件,建议的sql为:
SELECT
    m.from_name,
    u2. NAME AS to_name,
    m.reply
FROM
    USER u2
INNER JOIN (
    SELECT
        c.uid,
        u. NAME AS from_name,
        c.to_uid,
        c.content AS reply
    FROM
        COMMENT c
    INNER JOIN USER u ON u.uid = c.uid
    WHERE
        c.uid = 1
) m ON u2.uid = m.to_uid;

+-----------+---------+-------+
| from_name | to_name | reply |
+-----------+---------+-------+
| zgq       | qkl     | haha  |
| zgq       | pcb     | sdg   |
+-----------+---------+-------+

思路:
1.(评论者)
就是user表中的uid = comment表中的uid
2.(被评论者)
user表中的uid = comment表的to_uid
满足这个条件就ok了

select
(select name from user where user.uid = c.uid) as replyer,
(select name from user where user.uid = c.to_uid) as replyed,
c.content
from comment c
where id=1

理解下来数据都是在comment表中,只是comment.uid 和 comment.to_uid 需要转义成名称,
上述sql 有可能提供一些解决思路。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题