S
S
stasboiko2020-07-23 13:08:19
Oracle
stasboiko, 2020-07-23 13:08:19

How to join tables in SQL based on the result of the first query?

SELECT REGEXP_SUBSTR(listinfo, ';[^;]+') as list
  FROM import AS i
  JOIN lists as l ON l.listid = list
  WHERE i.userid = 1

We get an error that the list column is unknown because the 'list' column does not exist (this column is the result of the query). The result of 'list' is not a single value, but several at once. Is there a way to write a query in a query? First make a request that gets the data and then make another request based on the first request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mletov, 2020-07-23
@mletov

SELECT *
FROM
(
  SELECT REGEXP_SUBSTR(listinfo, ';[^;]+') as list
  FROM import
) AS i
JOIN lists as l 
ON l.listid = list
WHERE i.userid = 1

R
Rsa97, 2020-07-23
@Rsa97

The correct option would be to normalize the `import` table and move the many-to-many relationship to a separate table.
Now your regex will return only one occurrence of listinfo for each line, and even then with a semicolon at the beginning. For example, for the string '1;2;3' your REGEXP_SUBSTR will only return ';2'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question