如何加入2个mysql表 [英] how to join 2 mysql tables

查看:95
本文介绍了如何加入2个mysql表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想联接两个表以从两个表中获取数据,例如,考虑以下两个表:

I want to join two tables to get data from both tables, for example, consider two following tables:

Table users:
ID      user_name       email     ...    ....


Table messages:
ID      user_name       message     ...    ...

user_name是两个表中的公共列.如何连接两个表,以便可以从两个表中获取数据.例如,我想从表messages中选择"message",并从表"users"中选择"email",其中user_name是abc.

The user_name is common column in both tables. How can I join both tables so that I can get the data from both tables. For example, I want to select the "message" from Table messages and "email" from table "users" where user_name is abc.

推荐答案

使用:

SELECT u.*, m.*
  FROM USERS u
  JOIN MESSAGES m ON m.user_name = u.user_name
 WHERE u.user_name = 'abc'

...以查看在表中包含消息的所有用户.这意味着没有消息的用户将不会出现在输出中-因此,您可能需要使用以下内容:

...to see all the users who have messages in the tables. That means that users without messages will not appear in the output - so you might want to use the following instead:

   SELECT u.*, m.*
     FROM USERS u
LEFT JOIN MESSAGES m ON m.user_name = u.user_name
    WHERE u.user_name = 'abc'

我推荐:

  • 阅读 JOIN的直观说明.
  • 不使用user_name作为在表之间链接数据的标准,因为在此示例中,用户名可以更改,这将需要更新所有支持表.
  • 不使用ANSI-89联接语法,因为它不支持OUTER联接,因此应考虑弃用.我的示例是ANSI-92语法,并得到广泛支持.

这篇关于如何加入2个mysql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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