如何在 MySQL 中构建跨数据库查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1972943/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:53:19  来源:igfitidea点击:

How do I construct a cross database query in MySQL?

sqlmysql

提问by Avery

I've got two databases on the same server. The Google gave me some hints but there wasn't anything "official" that I could find. Could someone point me to the documentation that explains how to do this? An explanation using PHP would be useful as well. Thanks!

我在同一台服务器上有两个数据库。谷歌给了我一些提示,但我找不到任何“官方”的东西。有人可以指出我解释如何执行此操作的文档吗?使用 PHP 的解释也很有用。谢谢!

回答by OMG Ponies

I've got two databases on the same server. ...How do I construct a cross database query in MySQL?

我在同一台服务器上有两个数据库。...如何在 MySQL 中构建跨数据库查询?

You access other databases on the same MySQL instance by prefixing the table with the appropriate database name. IE:

您可以通过在表前加上适当的数据库名称来访问同一 MySQL 实例上的其他数据库。IE:

SELECT *
  FROM this_database.table_1 t1
  JOIN that_database.table_2 t2 ON t2.column = t1.column

Keep in mind

记住

A query executes with the credentials of the authentication used to set up the connection. If you want to query two tables simultaneously across two (or more) databases, the user used to run the query will need SELECT access to all databases involved.

使用用于设置连接的身份验证凭据执行查询。如果要跨两个(或更多)数据库同时查询两个表,用于运行查询的用户将需要对所有涉及的数据库进行 SELECT 访问。

Reference:

参考:

回答by Tyler Smith

SELECT * FROM DB1.myTable1 AS db1, DB2.myTable2 AS db2

回答by Sampson

http://www.dottedidesign.com/node/14provides the following example:

http://www.dottedidesign.com/node/14提供了以下示例:

SELECT 
  arbogast.node.nid as anid, 
  mcguffin.node.nid as mnid, 
  arbogast.node.title as atitle, 
  mcguffin.node.title as mtitle 
FROM arbogast.node, mcguffin.node 
WHERE arbogast.node.nid = 1 
  AND mcguffin.node.nid = arbogast.node.nid;

Where arbogastand mcguffinare different databases.

arbogastmcguffin不同的数据库。