我有一个查询,需要将其分成两部分并与 UNION 连接。两部分独立工作;但是,当我使用“SELECT * FROM (...)”时,出现错误:
SQLException in getScoutTroopDetails: java.sql.SQLException: Column 'at_cub_details.cd_id' not found.
我已将查询精简到显示错误的最低限度(即删除了联接、联合等)。
这有效:
String selectQry2 = (
"(SELECT at_cub_details.cd_id, at_cub_details.cd_scout_no, at_cub_details.cd_surname, " +
"at_cub_details.cd_first_name, at_cub_details.cd_dob, at_cub_details.cd_archived, " +
"at_section_details.sd_start_date " +
"FROM at_account_group, at_section_details, at_group, at_cub_details " +
"WHERE at_account_group.acc_id = ? " +
" AND at_account_group.grp_id = at_cub_details.grp_id " +
" AND at_cub_details.grp_id = at_group.grp_id " +
" AND at_cub_details.cd_id = at_section_details.cd_id " +
"GROUP BY at_cub_details.cd_surname, at_cub_details.cd_first_name, at_cub_details.cd_id)");
失败并出现上述错误:
String selectQry2 = ("SELECT * FROM " +
"(SELECT at_cub_details.cd_id, at_cub_details.cd_scout_no, at_cub_details.cd_surname, " +
"at_cub_details.cd_first_name, at_cub_details.cd_dob, at_cub_details.cd_archived, " +
"at_section_details.sd_start_date " +
"FROM at_account_group, at_section_details, at_group, at_cub_details " +
"WHERE at_account_group.acc_id = ? " +
" AND at_account_group.grp_id = at_cub_details.grp_id " +
" AND at_cub_details.grp_id = at_group.grp_id " +
" AND at_cub_details.cd_id = at_section_details.cd_id " +
"GROUP BY at_cub_details.cd_surname, at_cub_details.cd_first_name, at_cub_details.cd_id) AS a ");
最佳答案
首先,您需要使用别名引用表(您的 SQL 不必要地更长)。第二次尝试使用联接而不是所有这些表。第三,您的 java 代码无法引用该列,因为您现在正在从表 A
中查询。
CREATE TABLE `person` (
`idperson` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(80) NOT NULL,
PRIMARY KEY (`idperson`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
select a.idperson from (select p.idperson from test.person as p) as a;
希望对您有所帮助。
关于mysql - 如何使用 MySQL 将查询正确包装在 SELECT * FROM (...) 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796947/