编写查询以从两个数据库中获取数据

时间:2014-11-12 09:25:36

标签: sql database

以下是表名。两个数据库具有相同的表和列名。

field_data_field_name                                   
|  Entity_id| field_name_value|  
|    1      |       XYZ       |

field_data_field_address
-----------------------------------
|  Entity_id | field_address_value|  
|    1       |     abc            |

field_data_field_county
----------------------------------
|  Entity_id | field_county_value|  
|    1       | mumbai            |

field_data_field_select_area
---------------------------------------
|  Entity_id | field_select_area_value|  
|    1       | pension                |

users
------------------------------------
|  uid  | mail                     |  
|    1  | sopu.phadke080@gmail.com |

在基于Entity_id = uid的单个数据库中,我们成功连接表和数据。

following is query for single database.

SELECT 
field_data_field_name.field_name_value,
field_data_field_address.field_address_value,
field_data_field_county.field_county_value,
field_data_field_select_area.field_select_area_value,
users.mail
FROM users 
INNER JOIN field_data_field_name On field_data_field_name.entity_id= uid
INNER JOIN field_data_field_address On field_data_field_address.entity_id = uid
INNER JOIN field_data_field_county On field_data_field_county.entity_id = uid
INNER JOIN field_data_field_select_area On field_data_field_select_area.entity_id = uid

我创建此查询但不工作。请帮助我。

SELECT 
a.field_name_value,
b.field_address_value, 
c.field_county_value,
d.field_select_area_value,
e.field_name_value,
f.field_address_value,
g.field_county_value,
h.field_select_area_value
FROM 
dbeng.field_data_field_name As a,
dbeng.field_data_field_address As b,
dbeng.field_data_field_county As c,
dbeng.field_data_field_select_area As d,
inner join dbspa.field_data_field_name As e ON <field_data_field_name.field_name_value>=<field_data_field_name.field_name_value>,
inner join dbspa.field_data_field_address As f ON <field_data_field_address.field_address_value>=<field_data_field_address.field_address_value>,
inner join dbspa.field_data_field_county As g ON <field_data_field_county.field_county_value>=<field_data_field_county.field_county_value>,
inner join dbspa.field_data_field_select_area As h ON <field_data_field_select_area.field_select_area_value>=<field_data_field_select_area.field_select_area_value>
WHERE d.field_select_area_value ='Pensión Compensatoria' && h.field_select_area_value ='Pensión Compensatoria' && c.field_county_value ='Alameda' && g.field_county_value='Alameda'

2 个答案:

答案 0 :(得分:0)

将这些信息存储在两个不同的数据库中的概念听起来不对,但如果您需要从两者中获取数据,则必须执行UNION ALL

SELECT x.col1, x.col2
FROM
(
    SELECT a.col1, b.col1
    FROM db1.a
    JOIN db1.b ON ( ... )
  UNION ALL
    SELECT a.col1, b.col1
    FROM db2.a
    JOIN db2.b ON ( ... )
) x
WHERE x.col1 = ...

答案 1 :(得分:0)

选择Col1,Col2 来自DB1..Tbl1 在Tbl2.Col2 = DB1..Tbl1.Col1

上加入Tbl2

您可以使用以下语法访问另一个数据库的表:DatabaseName..TableName.ColumnName