2

假设您从 Web 服务器到 DBA 服务器的连接非常慢,并且您需要执行一系列三个查询来处理单个 Web 请求。有没有办法将查询组合成一个?假设以下场景

person.id person.name
1         James
2         Stacy

.

country.id country.name
1          USA
2          UK

.

location.person_id location.country_id
1                  1
1                  2

网络表单将发布两个变量,即 name="James" country="China" 并且您想要执行以下操作

  • “James”是否存在,如果不存在,插入 james
  • “中国”是否存在,如果不存在,插入china
  • “詹姆斯”是否住在“中国”,如果不插入关系

即类似的东西

select person.id, country.id, location.person_id
from person, country, location
where
    person.name="James" and
    country.name="China" and
    person.id=location.id and country.id=location.country_id

上面的查询没有用,因为如果人员、国家或地点不存在,它将不返回任何记录。

我知道使用存储过程可以做到这一点,但并非所有数据库都支持存储过程。

4

4 回答 4

4

解决方法很简单

SELECT (SELECT person.id from person WHERE person.name = 'James') as Name,
       (SELECT country.id from country WHERE country.name="China") as Country,
       (SELECT location.person_id from location WHERE person.id = location.id and country.id = location.country_id and person.name = 'James' and country.name="China") as Location
于 2012-04-05T06:21:12.393 回答
4

尝试这样的事情(使用 a UNION):

SELECT 
    id  as id,
    'PERSON' as type
FROM person
WHERE name = 'James'
UNION
SELECT 
    id as id,
    'COUNTRY' as type
FROM country
WHERE name = 'China'
UNION
SELECT 
    person_id as id,
    'LOCATION' as type
FROM location
JOIN person ON person.id = location.person_id
JOIN country ON country.id = location.country_id
WHERE person.name = 'James'
AND   country.name = 'China'

这将为您提供与各自名称匹配的所有行及其类型。看看 raheel shan 的回答,我认为这会更快,将其视为一种可行的替代方案 :-)

于 2012-04-05T06:20:38.730 回答
1

如果您使用的是 MSSQL(从您的问题中很难看出),它支持多个记录集。您可以通过连接字符串启用它,从存储过程中执行多项选择,并通过数据集作为多个数据表访问它...

于 2012-04-05T06:32:40.077 回答
0

如果您可以在一个数据集中获取整个数据,那么您应该使用完全连接

select person.*, country.*, location.*
from person
full join location
on person.id=location.id
full join country
on country.id=location.country_id
where isnull(person.name,'James')='James' and
isnull(country.name,'China')='China'
于 2012-04-05T06:29:11.437 回答