将两个单独的SQL查询的结果与“OR”组合在一起

时间:2011-02-15 10:25:40

标签: sql postgresql

框架:Rails 2.3.8 数据库;的PostgreSQL

我目前有以下SQL语句(由Rails生成)

SELECT "outbreaks".* FROM "outbreaks" INNER JOIN "bacterial_agents" ON bacterial_agents.outbreak_id = outbreaks.id INNER JOIN "bacteria" ON "bacteria".id = "bacterial_agents".bacterium_id WHERE (bacteria.name ILIKE E'%VTEC O157%')

SELECT "outbreaks".* FROM "outbreaks" INNER JOIN "viral_agents" ON viral_agents.outbreak_id = outbreaks.id INNER JOIN "virus" ON "virus".id = "viral_agents".virus_id WHERE (virus.name ILIKE E'%NOROVIRUS%')

使用下面的表格(我已经跳过了未使用的属性,并且布局/键命名归结为Rails约定)

outbreaks
  id

bacterial_agents
  id
  outbreak_id
  bacterium_id

bacteria
  id
  name

viral_agents
  id
  outbreak_id
  virus_id

viruses
  id
  name

任何想法如何加入上述两个带有“OR”条件的SQL语句,以选择与细菌表相关的爆发记录,其中的细菌名称就像“VTEC O157”或与病毒表有关virus.name就像“NOROVIRUS”?

*编辑

关于SQL的Rails生成的澄清 - 它当前输出以下SQL

SELECT "outbreaks".* FROM "outbreaks" INNER JOIN "bacterial_agents" ON bacterial_agents.outbreak_id = outbreaks.id INNER JOIN "bacteria" ON "bacteria".id = "bacterial_agents".bacterium_id INNER JOIN "viral_agents" ON outbreaks.id = viral_agents.outbreak_id INNER JOIN "viruses" ON "viral_agents".virus_id = "viruses".id WHERE ((bacteria.name ILIKE E'%VTEC O157%') AND (viruses.name ILIKE E'%NOROVIRUS%')) LIMIT 1

基本上我想将前两个语句的组合结果输出为与上述语句类似的格式(用“OR”条件代替“AND”)。但是,如果这不可能,我只需编写一个范围来代替SQL联合。

根据下面的回复来判断,我将与两个单独的声明联合,欢呼:)

2 个答案:

答案 0 :(得分:5)

我认为您正在混淆OR与 SQL联合运算符以加入两个查询的返回。

OR用于管理语句的WHERE部分中的条件,而union用于将一个查询附加到另一个查询。

您应该注意,仅当两个查询具有相同的域时,联合才有效。通过快速查看您的查询,它应该完全按照您的想法进行。

试试这个:

SELECT "outbreaks".* FROM "outbreaks" INNER JOIN "bacterial_agents" ON bacterial_agents.outbreak_id = outbreaks.id INNER JOIN "bacteria" ON "bacteria".id = "bacterial_agents".bacterium_id WHERE (bacteria.name ILIKE E'%VTEC O157%')
UNION
SELECT "outbreaks".* FROM "outbreaks" INNER JOIN "viral_agents" ON viral_agents.outbreak_id = outbreaks.id INNER JOIN "virus" ON "virus".id = "viral_agents".virus_id WHERE (virus.name ILIKE E'%NOROVIRUS%')

答案 1 :(得分:2)

在查询之间放置一个UNION ALL

SELECT "outbreaks".* 
  FROM "outbreaks"
  INNER JOIN "bacterial_agents"     ON bacterial_agents.outbreak_id = outbreaks.id 
  INNER JOIN "bacteria"         ON "bacteria".id = "bacterial_agents".bacterium_id
WHERE (bacteria.name ILIKE E'%VTEC O157%')

UNION ALL

SELECT "outbreaks".*
   FROM "outbreaks"
   INNER JOIN "viral_agents"    ON viral_agents.outbreak_id = outbreaks.id 
   INNER JOIN "virus"       ON "virus".id = "viral_agents".virus_id
 WHERE (virus.name ILIKE E'%NOROVIRUS%')