UNION查询不起作用

时间:2013-03-02 14:01:03

标签: mysql sql union-all

这是我的UNION ALL查询,但它不起作用,我不知道为什么,这似乎是正确的

        SELECT 
                ID AS IDzivotinja, zivotinja 
                FROM zivotinje WHERE IDveterinar=$ID
        UNION ALL
        SELECT 
                ID AS IDsimptom, simptom 
                FROM simptomi WHERE IDveterinar=$ID
        UNION ALL
        SELECT
                ID AS IDterminza, terminza
                FROM termniniza WHERE IDveterinar=$ID

2 个答案:

答案 0 :(得分:1)

请注意,UNION中的每个SELECT语句必须具有相同的列数。列还必须具有类似的数据类型。此外,每个SELECT语句中的列必须具有相同的顺序。以下SQL查询应该起作用。请试一试。

编辑:如果相应的列没有相同的数据类型,您可以将它们转换为相同的数据类型,如下所示:

 SELECT 
        ID AS IDzivotinja, CAST(zivotinja AS CHAR) AS Col2
        FROM zivotinje WHERE IDveterinar=$ID
UNION ALL
SELECT 
        ID AS IDzivotinja, CAST(simptom  AS CHAR) AS Col2
        FROM simptomi WHERE IDveterinar=$ID
UNION ALL
SELECT
        ID AS IDzivotinja, CAST(terminza AS CHAR) AS Col2
        FROM termniniza WHERE IDveterinar=$ID

答案 1 :(得分:1)

列必须相互匹配。

SELECT  ID, zivotinja as ColName, 'zivotinje' tableName
FROM    zivotinje 
WHERE   IDveterinar=$ID
UNION ALL
SELECT  ID, simptom as ColName, 'simptomi' tableName
FROM    simptomi 
WHERE   IDveterinar=$ID
UNION ALL
SELECT  ID, terminza as ColName, 'termniniza' tableName
FROM    termniniza 
WHERE   IDveterinar=$ID

还有一件事,这只是猜测

如果列zivotinjasimptomterminza只是用户定义值(,其目的是用于定义值来自哪个表的位置< / em>)然后你需要用单引号包装它。

SELECT  ID, 'zivotinja' as ColName
FROM    zivotinje 
WHERE   IDveterinar=$ID
UNION ALL
SELECT  ID, 'simptom' as ColName
FROM    simptomi 
WHERE   IDveterinar=$ID
UNION ALL
SELECT  ID, 'terminza' as ColName
FROM    termniniza 
WHERE   IDveterinar=$ID