让我们说我有一个USERS表,其中有四个用户:
+----+-------+
| id | login |
+----+-------+
| 1 | guest |
| 2 | admin |
| 3 | alice |
| 4 | bob |
+----+-------+
我想将其与任意属性列表组合。说我的清单是:“ alice”,“ bob”,“ charles”,“ dan”。我想写一个看起来像这样的选择(然后插入到另一个表中)。
+----+-------+-------------+
| id | login | friend_name |
+----+-------+-------------+
| 1 | guest | alice |
| 2 | admin | bob |
| 3 | alice | charles |
| 4 | bob | dan |
+----+-------+-------------+
当前尝试:
SELECT u.id,
u.name,
vals.column_value
FROM users u
INNER JOIN TABLE(sys.odcivarchar2list('alice', 'bob', 'charles', 'dan')) vals
ON vals.column_value IS NOT NULL ;
仅这将创建笛卡尔乘积。结果将为每个用户包括四行:
+----+-------+-------------+
| id | login | friend_name |
+----+-------+-------------+
| 1 | guest | alice |
| 1 | guest | bob |
| 1 | guest | charles |
| 1 | guest | dan |
| 2 | admin | alice |
| 2 | admin | bob |
| 2 | admin | charles |
| 2 | admin | dan |
| 3 | alice | alice |
| 3 | alice | bob |
| 3 | alice | charles |
| 3 | alice | dan |
| 4 | bob | alice |
| 4 | bob | bob |
| 4 | bob | charles |
| 4 | bob | dan |
+----+-------+-------------+
这是行不通的,但这是我想要做的:
SELECT u.id,
u.name,
vals.column_value
FROM users u
INNER JOIN TABLE(sys.odcivarchar2list('alice', 'bob', 'charles', 'dan')) vals
ON vals.rownum = u.rownum ;
当然,它不起作用,因为两个表没有rownum属性。
如何编写一个选择,将选择列表中的值列表插入列中而不将它们相乘?
答案 0 :(得分:2)
可能还有其他方法,但是一种方法是:
SELECT u.id, u.name, vals.column_value
FROM (SELECT u.*, rownum as seqnum
FROM users u
) u JOIN
(SELECT vals.*, rownum as seqnum
FROM TABLE(sys.odcivarchar2list('alice', 'bob', 'charles', 'dan')) vals
) vals
ON vals.rn = u.rn ;