查找2个varrays是否具有相似的值

时间:2017-10-13 10:00:32

标签: sql oracle

只是跟进我的previous question,我想知道如何检索有相似值的行,即2个游戏是否有2个或更多共同主题。

经过一些网上挖掘后,我认为下面的查询尽可能接近......但它显然不起作用。如果我指定我正在寻找的主题,我上一个问题中的评论可能会有效。

select title
from (select c.*, count(table(c.gametheme)) over (partition by 
table(c.gametheme)) as theme_count
from game_table c)
WHERE theme_count > 1

1 个答案:

答案 0 :(得分:1)

如果您使用的是集合而不是VARRAY,那么您不限于可以存储的主题数量,您可以使用MULTISET INTERSECT [ALL|DISTINCT]运算符和CARDINALITY函数:< / p>

SQL Fiddle

Oracle 11g R2架构设置

CREATE OR REPLACE TYPE Varchar20List AS TABLE OF VARCHAR2(20)
/ 

CREATE OR REPLACE TYPE Game_Type AS OBJECT(
  Title VARCHAR2(50),
  GameTheme Varchar20List
)
/
CREATE TABLE Game_Table of Game_Type
NESTED TABLE GameTheme STORE AS GameTheme_tab
/
INSERT INTO Game_Table
VALUES('Game A' , Varchar20List( 'Action', 'FPS') )
/
INSERT INTO Game_Table
VALUES('Game B' , Varchar20List( 'Action', 'FPS', 'P2W') )
/
INSERT INTO Game_Table
VALUES('Game C' , Varchar20List( 'FPS', 'P2W' ) )
/

查询1

SELECT *
FROM   game_table a
       INNER JOIN
       game_table b
       ON (
         a.title < b.title
         AND
         CARDINALITY( a.GameTheme MULTISET INTERSECT b.GameTheme ) > 1
       )

<强> Results

|  TITLE |      GAMETHEME |  TITLE |      GAMETHEME |
|--------|----------------|--------|----------------|
| Game A |     Action,FPS | Game B | Action,FPS,P2W |
| Game B | Action,FPS,P2W | Game C |        FPS,P2W |

如果你想使用VARRAY s来做,那么:

SQL Fiddle

Oracle 11g R2架构设置

CREATE OR REPLACE TYPE Varchar20List AS VARRAY(3) OF VARCHAR2(20)
/ 

CREATE OR REPLACE TYPE Game_Type AS OBJECT(
  Title VARCHAR2(50),
  GameTheme Varchar20List
)
/
CREATE TABLE Game_Table of Game_Type
--NESTED TABLE GameTheme STORE AS GameTheme_tab
/
INSERT INTO Game_Table
VALUES('Game A' , Varchar20List( 'Action', 'FPS') )
/
INSERT INTO Game_Table
VALUES('Game B' , Varchar20List( 'Action', 'FPS', 'P2W') )
/
INSERT INTO Game_Table
VALUES('Game C' , Varchar20List( 'FPS', 'P2W' ) )
/

查询1

SELECT *
FROM   game_table a
       INNER JOIN
       game_table b
       ON (
         a.title < b.title
         AND
         2 <= ( SELECT COUNT(*)
                FROM   TABLE( a.GameTheme ) ag
                       INNER JOIN TABLE( b.GameTheme ) bg
                       ON ( ag.COLUMN_VALUE = bg.COLUMN_VALUE ) )
       )

<强> Results

|  TITLE |      GAMETHEME |  TITLE |      GAMETHEME |
|--------|----------------|--------|----------------|
| Game A |     Action,FPS | Game B | Action,FPS,P2W |
| Game B | Action,FPS,P2W | Game C |        FPS,P2W |