1

I've got a table views with a column containing XML documents (stored as text). Here's a simplified version:

<?xml version="1.0"?>
<view>
  <image>
    <sequence>
      <param name="scan">129</param>
    </sequence>
  </image>
  <image>
    <sequence>
      <param name="scan">1</param>
    </sequence>
  </image>
  [...]
</view>

Another table contains the scans referenced in the XML. If refactoring into a new table is impractical at the moment, how do I connect the two tables in an SQL query?

1 Answer 1

3

If your PostgreSQL has been compiled with --with-libxml, the following query should work:

SELECT ...
  FROM views
  JOIN scans ON scans.id = ANY (
           xpath(
               '/view/image/sequence/param[@name = "scan"]/text()',
                views.xml::xml)::text[]::int[])
;

That is:

  1. Cast views.xml from text to xml.
  2. Get all the scan ID values as an array of xml using xpath().
  3. Cast the xml array to an array of text and then an array of int (you can't cast xml[] to int[] directly, at least in PostgreSQL 9.2).
  4. Check that at least one of the scan IDs from the XML matches.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.