在一个查询中执行多个SQL查询(也称为保存两次网络往返)

时间:2012-04-05 06:10:14

标签: sql

假设从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”,您想要执行以下操作

  • “詹姆斯”是否存在,如果没有,请插入詹姆斯
  • “中国”是否存在,如果没有,请插入中国
  • “詹姆斯”是否住在“中国”,如果没有插入关系

之类的东西
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 个答案:

答案 0 :(得分:4)

尝试这样的事情(使用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的回答我认为会更快,认为这个是一个可行的选择: - )

答案 1 :(得分: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

答案 2 :(得分:1)

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

答案 3 :(得分: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'
相关问题