Question

I have a query something like this (no, my tables and fields are not called by these names, but the structure is the same) -

SELECT table1.id, table2.id, table1.phone1
FROM table1 LEFT OUTER JOIN
    table3 ON table3.id = table1.id LEFT OUTER JOIN
    table2 ON table3.id2 = table2.id    
    WHERE table1.phone1 IS NOT NULL AND LTRIM(RTRIM(table1.phone1)) <> ''

UNION

SELECT table1.id, table2.id, table1.phone2
FROM table1  LEFT OUTER JOIN
    table3 ON table3.id = table1.id LEFT OUTER JOIN
    table2 ON table3.id2 = table2.id    
WHERE table1.phone2 IS NOT NULL AND LTRIM(RTRIM(table1.phone2)) <> ''

UNION

SELECT table1.id, table2.id, table2.phone
FROM table1 LEFT OUTER JOIN
    table3 ON table3.id = table1.id LEFT OUTER JOIN
    table2 ON table3.id2 = table2.id    
WHERE table2.phone IS NOT NULL AND LTRIM(RTRIM(table2.phone)) <> ''

It runs fine. But, when I try to select from it (which I will eventually try to manipulate with group bys, etc., but for now just tried a simple select), like so:

SELECT * FROM
    ( SELECT table1.id, table2.id, table1.phone1
    FROM table1 LEFT OUTER JOIN
        table3 ON table3.id = table1.id LEFT OUTER JOIN
        table2 ON table3.id2 = table2.id    
        WHERE table1.phone1 IS NOT NULL AND LTRIM(RTRIM(table1.phone1)) <> ''

    UNION

    SELECT table1.id, table2.id, table1.phone2
    FROM table1  LEFT OUTER JOIN
        table3 ON table3.id = table1.id LEFT OUTER JOIN
        table2 ON table3.id2 = table2.id    
    WHERE table1.phone2 IS NOT NULL AND LTRIM(RTRIM(table1.phone2)) <> ''

    UNION

    SELECT table1.id, table2.id, table2.phone
    FROM table1 LEFT OUTER JOIN
        table3 ON table3.id = table1.id LEFT OUTER JOIN
        table2 ON table3.id2 = table2.id    
    WHERE table2.phone IS NOT NULL AND LTRIM(RTRIM(table2.phone)) <> '' )

I get the error:

Incorrect syntax near ')'.

What am I doing wrong?

Was it helpful?

Solution

You missed naming the subselect. Close with something like ...) sub_query_name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top