一个mysql多表查询的问题

WBOY
Release: 2016-06-06 20:46:09
Original
927 people have browsed it

求问一个数据库问题。 user表有一个real_name字段,表示用户姓名。plag表有两个字段 user_id1, user_id2, 现在要查询plag表中的所有信息,同时把user_id1, user_id2对应user表中的real_name也输出出来。怎么写sql?

比如: user表用两条记录:
id: 1 real_name: Tom
id: 2 real_name: Mike

plag表有这样一条记录
id: 1 user_id1: 1 user_id2: 2

我希望能把plag以这样的形式输出:
id: 1 name1: Tom name2: Mike

求大神给出sql并解释

回复内容:

求问一个数据库问题。 user表有一个real_name字段,表示用户姓名。plag表有两个字段 user_id1, user_id2, 现在要查询plag表中的所有信息,同时把user_id1, user_id2对应user表中的real_name也输出出来。怎么写sql?

比如: user表用两条记录:
id: 1 real_name: Tom
id: 2 real_name: Mike

plag表有这样一条记录
id: 1 user_id1: 1 user_id2: 2

我希望能把plag以这样的形式输出:
id: 1 name1: Tom name2: Mike

求大神给出sql并解释

<code>select plag.id, group_concat(user.name order by user.id) as real_names from plag left join user on plag.user_id1 = user.id or plag.user_id2 = user.id 
</code>
Copy after login

这句虽然输出有点出入,但是应该也符合题主的需求,输出结果应该为:

<code>id | realnames
1 | Tom,Mike 
</code>
Copy after login

得到的 realnames 是以 user.id 按序排列的,结果集是可操作的。
下面这句可以得到楼主希望的输出:

<code>select plag.id,(select user.name from plag inner join user on user.id = plag.user_id1) as name1, (select user.name from plag inner join user on user.id = plag.user_id2) as name2 from plag
</code>
Copy after login

输出应该为:

<code>id | name1 | name2
1 | Tom | Mike
</code>
Copy after login

应该使用 INNER JOIN 方式吧

参考 http://www.w3school.com.cn/sql/sql_join_inner.asp

<code>select p.id, u1.real_name as name1, u2.real_name as name2
from plag p, user as u1, user as u2
where p.user_id1 = u1.id and p.user_id2 = u2.id;
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template