10

The following query:

select unnest(Table2.L) as X, unnest(Table1.O) 
from Table1, Table2 
where Table1.code = Table2.code 
order by X ;

produces the desired results. I would, however, like to exclude (unnested) rows which match some value. Adding a condition to the query, such as the following:

and unnest(Table2.L) != '-'

obviously does not work. Is this possible? How?

9

If by unnest(Table2.L) != '-' you mean

throw out all the unnested elements that are '-'

then use a derived table and filter out the unnested values you don't want:

select *
from (
    select unnest(Table2.L) as X, unnest(Table1.O) 
    from Table1 join Table2 on Table1.code = Table2.code
) dt
where X != '-'
order by X ;

If you mean

ignore all rows from Table2 where L contains '-'

then you can use the @> operator to check if L contains a certain element:

select unnest(Table2.L) as X, unnest(Table1.O)
from Table1 join Table2 on Table1.code = Table2.code
where not Table1.L @> ARRAY['-']

or you could use ANY:

select unnest(Table2.L) as X, unnest(Table1.O)
from Table1 join Table2 on Table1.code = Table2.code
where not '-' = any(Table1.L)

And do yourself a favor by forgetting that implicit joins exist, always use explicit join conditions.

1
  • I meant the first scenario in your answer, but thanks for the additional information too.
    – SabreWolfy
    Jun 26, 2012 at 21:22
3

Another way of doing it:

SELECT x, y
FROM  (SELECT code, unnest(l) AS x FROM table1) t1
JOIN  (SELECT code, unnest(o) AS y FROM table2) t2 USING (code)
WHERE  x <> '-'
ORDER  BY x;

May of may not be faster. Depends on how selective the WHERE clause is. Run a quick EXPLAIN ANYLYZE.

Note that I untangled table1 and table2, which are reversed in the example. If you are confused by all the clarity, try substituting x -> y in the WHERE and ORDER BY clause.

If you actually want to eliminate occurrences of - on both sides, add AND y <> '-' to the WHERE clause - making it symmetric (no cuonfusion possible).
I would also ORDER BY x, y, if x is not guaranteed to be unique, to make the sort order stable.

Demo on sqlfiddle.

2
  • There are ~350 rows which match after excluding the '-' rows. Your answer gives ~34000, so something is wrong somewhere :) I'm checking it now. Also, I was able to include additional columns from Table2 in the query which "mu is too short" provided, but am not able to do so with your answer.
    – SabreWolfy
    Jun 26, 2012 at 21:34
  • There must be some kind of misunderstanding. Added a bit to my answer to clarify. Jun 26, 2012 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.