找到第一个结果时短路UNION查询

时间:2016-11-30 20:16:28

标签: sql postgresql

我已经构建了一个非常基本的UNION查询,以确定传递给我的查询的UUID的“类型”,如下所示:

(
  SELECT
  CASE WHEN id IS NOT NULL THEN 'player_id' ELSE '' END AS uuid_type 
  FROM db.players
  WHERE id = $1
)
UNION
(
  SELECT
  CASE WHEN id IS NOT NULL THEN 'game_id' ELSE '' END AS uuid_type 
  FROM db.games
  WHERE id = $1
)
UNION
(
  SELECT
  CASE WHEN id IS NOT NULL THEN 'location_id' ELSE '' END AS uuid_type 
  FROM db.locations
  WHERE id = $1
)
UNION
(
  SELECT
  CASE WHEN id IS NOT NULL THEN 'promo_id' ELSE '' END AS uuid_type 
  FROM db.promos
  WHERE id = $1
)

是否有办法将此查询“短路”,以便在找到结果时停止。例如,如果第一个子查询成功并且uuid_type设置为player_id,我希望查询停止,因为现在不需要检查其他三个表。

2 个答案:

答案 0 :(得分:4)

我没有Postgres可以测试它。但它应该像这样工作:

SELECT t.uuid_type
FROM (
    (
      SELECT
      CASE WHEN id IS NOT NULL THEN 'player_id' ELSE '' END AS uuid_type 
      FROM db.players
      WHERE id = $1
    )
    UNION ALL
    (
      SELECT
      CASE WHEN id IS NOT NULL THEN 'game_id' ELSE '' END AS uuid_type 
      FROM db.games
      WHERE id = $1
    )
    UNION ALL
    (
      SELECT
      CASE WHEN id IS NOT NULL THEN 'location_id' ELSE '' END AS uuid_type 
      FROM db.locations
      WHERE id = $1
    )
    UNION ALL
    (
      SELECT
      CASE WHEN id IS NOT NULL THEN 'promo_id' ELSE '' END AS uuid_type 
      FROM db.promos
      WHERE id = $1
    )
) t LIMIT 1;

LIMIT 1将结果限制为单行。通过将UNION替换为UNION ALL,查询应该更有效率,并且不再需要识别和删除重复项。

答案 1 :(得分:3)

合并怎么样?

Select coalesce((Select 'player_id' from db.players where id = $1), 
                (Select 'game_id' from db.players where id = $1), 
                (Select 'location_id' from db.players where id = $1), 
                (Select 'promo_id' from db.players where id = $1))