Postgre報錯:ERROR: UNION types numeric and character varying cannot be matched


  今天遇到一個問題,Postgre的一個查詢功能突然報錯“ERROR:  UNION types numeric and character varying cannot be matched,LINE 6: ...ipematerial,b.geom,b.pressurerating,b.pipelength, pipediam,b...”,在對兩個結果集進行合並查詢時報錯,數字和字符串的類型不能合並,SQL如下:

SELECT
    a.gid AS gid,
    a. NAME AS NAME,
    a.pipematerial,
    a.geom,
    a.pressurerating,
    a.pipelength,
    a.pipediam,
    a.wallthickness,
    a.source,
    a.target
FROM
    zy a
WHERE
    a.projectId = '2c91808f7cc0e652017ccfc7f7ea016f'
UNION ALL
    SELECT
        b.id AS gid,
        b. NAME AS NAME,
        b.pipematerial,
        b.geom,
        b.pressurerating,
        b.pipelength,
        b.pipediam,
        b.wallthickness,
        b.source,
        b.target
    FROM
        digital_edit_pipeline b
    WHERE
        b.condition_id = '2c9180887d45f311017d55857e9b02ac'
    AND b. ENABLE = 1

  查了一下,是digital_edit_pipeline 表的pipediam字段被改成了字符串類型,這是另外一個同事出於某種原因進行了修改,導致這個地方報錯了,解決也很簡單,把兩個表的這個字段轉換成相同的數據類型就可以了,用to_number (obj, '99999.999')就可以把字符串轉數字,修改后的SQL如下:

SELECT
    a.gid AS gid,
    a. NAME AS NAME,
    a.pipematerial,
    a.geom,
    a.pressurerating,
    a.pipelength,
    a.pipediam,
    a.wallthickness,
    a.source,
    a.target
FROM
    zy a
WHERE
    a.projectId = '2c91808f7cc0e652017ccfc7f7ea016f'
UNION ALL
    SELECT
        b.id AS gid,
        b. NAME AS NAME,
        b.pipematerial,
        b.geom,
        b.pressurerating,
        b.pipelength,
        to_number (b.pipediam, '99999.999') AS pipediam,
        b.wallthickness,
        b.source,
        b.target
    FROM
        digital_edit_pipeline b
    WHERE
        b.condition_id = '2c9180887d45f311017d55857e9b02ac'
    AND b. ENABLE = 1

  如上,就可以解決之前的報錯了。如果需要截取字符串后再轉數字,可以用trim()函數,如trim(both 'abc' from pipediam),可以去除pipediam字段中包含abc的字符串,完整的書寫就是to_number(trim(both 'abc' from pipediam), '9999.999') AS pipediam。

  其實不管是Postgre還是MySQL、Oracle等其他數據,這個解決思路都是一樣,差別可能就是每個數據庫的函數不太一樣。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM