1

这是我的 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
4

2 回答 2

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
于 2013-03-02T14:03:52.703 回答
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

还有一件事,这只是一个猜测

如果列zivotinja, simptom,terminza只是用户定义的值(它的目的是用来定义值来自哪里的表),那么您需要用单引号将其括起来。

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
于 2013-03-02T14:05:11.423 回答