如何基于主表中的值从另一个表中选择另外两个列? [英] How to select two additional columns from another table based on values in the main table?

查看:62
本文介绍了如何基于主表中的值从另一个表中选择另外两个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为maintable的表,其中有3列:iduserid1userid2.

I have a table named maintable with 3 columns: id, userid1 and userid2.

另一个名为users的表由userid键控,并以name作为列.

Another table named users is keyed by userid, and has name as a column.

我想选择以下内容:

SELECT maintable.*, users.name AS username1, users.name AS username2 
FROM maintable, users 
WHERE ...

基本上,我想获取maintable行中的所有列,并在末尾添加两列,以从users表中绘制userid1userid2的名称.

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.

我不确定如何为这样的查询设置where子句的格式.

I'm unsure how to format the where clause for a query like this.

推荐答案

您需要与用户加入两次:

You need to join twice with users:

SELECT m.*, u1.name, u2.name
FROM maintable m 
INNER JOIN users u1 ON (m.userid1 = u1.userid)
INNER JOIN users u2 ON (m.userid2 = u2.userid)

您可以在此处阅读有关MySQL JOIN语法的文档.

You can read the documentation about MySQL JOIN Syntax here.

这篇关于如何基于主表中的值从另一个表中选择另外两个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆