Search code examples
sqloracleoracle-sqldevelopersqlplus

Oracle SQL Inserting multiple rows into a table while referencing 2 FK


I'm trying to insert values id_team_FK and id_location_FK which both come from the same table. For example id_team_FK = 4 and id_location_FK = 150. The problem is, id_team_FK must be a randomly chosen value from team_table ( this works) and I need to know the exact number ( for example 4 ) to realize which id_location_FK is assigned to it ( for example 150 ). How do I make it work ?

   insert into test (PK, id_team_FK,id_location_FK)
values (1,
-- Selects random number from table
(select * from  (id_team_FK from team_table  order by dbms_random.random) where rownum=1),
-- needs to know the value of id_team_FK to know what select...
(select * from ( select id_location_FK from team_table) where team_table.id_team_FK = id_team_FK));

Solution

  • How about CTEs? Select ID_TEAM_FK first, use it to fetch ID_LOCATION_FK, insert the result.

    INSERT INTO test (pk, id_team_fk, id_location_fk)
       WITH
          temp
          AS
          -- select random number from table
             (SELECT id_team_fk
                FROM (  SELECT id_team_FK
                          FROM team_table
                      ORDER BY DBMS_RANDOM.random)
               WHERE ROWNUM = 1),
          temp2
          AS
          -- now you know ID_TEAM_FK (you fetched it in the TEMP CTE), so - fetch ID_LOCATION_FK
             (SELECT id_team_fk, id_location_fk
                FROM (SELECT a.id_team_fk, b.id_location_FK
                        FROM team_table a CROSS JOIN temp b
                       WHERE a.id_team_FK = b.id_team_FK))
       SELECT 1, id_team_fk, id_location_fk
         FROM temp2;