作为兼容性:“在mysql和sqlserver中使用,而不是oracle?

wvt8vs2t  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(387)

这个问题在这里已经有答案了

在oracle中“as”别名不起作用(3个答案)
9个月前关门了。
我试着用黑客银行解决这个问题https://www.hackerrank.com/challenges/symmetric-pairs/problem
以下代码适用于mysql和mssqlserver,但不适用于oracle。有人告诉我为什么吗?

  1. with T as (
  2. select x,y, row_number() over (order by x,y) as rnum from functions
  3. )
  4. select distinct a.x,a.y from T as a, T as b
  5. where a.x = b.y and b.x=a.y and a.x<=a.y and a.rnum!=b.rnum
  6. order by a.x,a.y;

似乎如果我删除了“as”,那么它在oracle中就可以工作了。为什么?

  1. with T as (
  2. select x,y, row_number() over (order by x,y) as rnum from functions
  3. )
  4. select distinct a.x,a.y from T a, T b
  5. where a.x = b.y and b.x=a.y and a.x<=a.y and a.rnum!=b.rnum
  6. order by a.x,a.y;
d6kp6zgx

d6kp6zgx1#

甲骨文不允许 as 用于表别名。您可以使用以下命令编写查询 FROM 条款:

  1. from T a cross join
  2. T b

然而,这是愚蠢的,因为你不打算 cross join . 在编写查询时,它将是:

  1. with T as (
  2. select x, y, row_number() over (order by x, y) as rnum
  3. from functions
  4. )
  5. select distinct a.x, a.y
  6. from T a join
  7. T b
  8. on a.x = b.y and b.x = a.y and a.x <= a.y and a.rnum <> b.rnum
  9. order by a.x, a.y;

如果这是一个有点难以破译这是应该做的。但我想它是想 x / y 多次出现的组合。如果是,请使用 count(*) 取而代之的是:

  1. with f as (
  2. select x, y, count(*) over (partition by x, y) as cnt
  3. from functions f
  4. )
  5. select f.x, f.y
  6. from f
  7. where cnt > 1;

这要简单得多,而且应该有更好的性能。而且,它应该在问题中提到的所有数据库中工作。

展开查看全部

相关问题