MySQL 如何根据主表中的值从另一个表中选择两个附加列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5007122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select two additional columns from another table based on values in the main table?
提问by CP1985
I have a table named maintable
with 3 columns: id
, userid1
and userid2
.
我有一个以maintable
3 列命名的表:id
,userid1
和userid2
.
Another table named users
is keyed by userid
, and has name
as a column.
另一个名为的表以users
为键userid
,并name
作为一列。
I want to select something along the lines of:
我想选择以下内容:
SELECT maintable.*, users.name AS username1, users.name AS username2
FROM maintable, users
WHERE ...
Basically I want to get all the columns in the maintable
row, and add two columns at the end that will draw the names for userid1
and userid2
from the users
table.
基本上我想获取行中的所有列maintable
,并在最后添加两列,以便为表格绘制名称userid1
和userid2
从users
表格中提取名称。
I'm unsure how to format the where clause for a query like this.
我不确定如何为这样的查询格式化 where 子句。
采纳答案by Pablo Santa Cruz
回答by Paulraj
something like this,
像这样的东西,
select m.*,
(select u1.name from users as u1 where m.userid1 = u1.userid) as username1,
(select u2.name from users as u2 where m.userid2 = u2.userid) as username2
from
maintable as m