2016-04-27 54 views
1

用Apache Derby(10.12.1.1),我創建了下面的表格:Apache Derby:列引用「xx」無效,或者是無效表達式的一部分。

CREATE TABLE ROWCONTENT(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY, 
MD5SUM CHAR(32) UNIQUE, 
CONTENT CLOB, 
CONTIG VARCHAR(20), 
START INT, 
STOP INT, 
REF VARCHAR(50) NOT NULL 
); 

CREATE TABLE VCF(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY, 
NAME VARCHAR(255) 
); 

CREATE TABLE VCFROW(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY, 
VCF_ID INTEGER CONSTRAINT row2vcf REFERENCES VCF, 
ROW_ID INTEGER CONSTRAINT row2content REFERENCES ROWCONTENT 
); 

但是當我嘗試SELECT使用下面的語句

SELECT 
VCF.ID,VCF.NAME, COUNT(VCFROW.ID) as "COUNT_VARIANTS" 
FROM 
    VCF,VCFROW,ROWCONTENT 
WHERE 
    VCFROW.VCF_ID=VCF.ID AND 
    VCFROW.ROW_ID = ROWCONTENT.ID AND 
    ROWCONTENT.CONTIG IS NOT NULL 
GROUP BY VCF.ID 

我得到以下異常:

java.sql.SQLSyntaxErrorException: Column reference 'VCF.NAME' is invalid, or is part of an invalid expression. For a SELECT list with a GROUP BY, the columns and expressions being selected may only contain valid grouping expressions and valid aggregate expressions. 
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source) 
    at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) 
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) 
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) 
    at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) 
    at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) 
    at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) 
    at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source) 

你知道爲什麼嗎? 謝謝。

回答

3

首先使用顯式JOIN

... 
FROM VCF 
JOIN VCFROW 
    ON VCFROW.VCF_ID=VCF.ID 
JOIN ROWCONTENT 
    ON VCFROW.ROW_ID = ROWCONTENT.ID 
WHERE ROWCONTENT.CONTIG IS NOT NULL 
GROUP BY VCF.ID; 

您還可以添加表的別名,所以你不必寫整個表名。


VCF.NAME不是GROUP BY一部分,它不與聚合功能纏繞。

根據使用需求:

GROUP BY VCF.ID,VCF.NAME 
-- or 
SELECT VCF.ID, MAX(VCF.NAME) AS NAME, COUNT(VCFROW.ID) AS COUNT_VARIANTS 

相關:Group by clause in mySQL and postgreSQL, why the error in postgreSQL?

在標準的SQL,包括GROUP BY子句中不能引用非聚合列在選擇列表不屬於查詢在GROUP BY子句中命名