鍍金池/ 問答/Java  PHP  C++  HTML/ MySQL一條語句同時(shí)關(guān)聯(lián)另一個(gè)表的兩個(gè)字段

MySQL一條語句同時(shí)關(guān)聯(lián)另一個(gè)表的兩個(gè)字段

現(xiàn)在遇到了個(gè),在設(shè)計(jì)一個(gè)mysql文章評論部分時(shí),遇到一個(gè)MySQL的語句不會寫。先看表:

圖片描述

最后想要的結(jié)果是: 張三 回復(fù) 李四:文章很好
根據(jù)我的經(jīng)驗(yàn),用MySQL的where方法只能獲得comment表中uid或者to_uid在user中的姓名,比如:

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

上面語句的出來的是評論表中評論者(張三)在用戶表的name值,李四的name值沒能到,有什么辦法可以同時(shí)得到張三和李四的name值的呢,謝謝大家指點(diǎn)一下!

回答
編輯回答
巫婆

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

理解下來數(shù)據(jù)都是在comment表中,只是comment.uid 和 comment.to_uid 需要轉(zhuǎn)義成名稱,
上述sql 有可能提供一些解決思路。

2018年4月15日 14:23
編輯回答
焚音

思路:
1.(評論者)
就是user表中的uid = comment表中的uid
2.(被評論者)
user表中的uid = comment表的to_uid
滿足這個(gè)條件就ok了

2017年5月26日 01:32
編輯回答
涼心人
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);
拼接最終結(jié)果
或
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   |
+-----------+---------+-------+
2017年7月26日 12:12
編輯回答
故人嘆
select * from user u, user tu, comment c where u.uid = c.uid and tu.uid = c.to_uid

試試?

2017年3月15日 08:09