错误代码:1052 - 列' idk'在字段列表中是不明确的

时间:2018-04-24 02:14:17

标签: mysql

您好我尝试创建查询并添加此查询错误:

JOIN matakuliah ON nilai.idk = matakuliah.idk
WHERE matakuliah.semester = 1

完整查询:

SET @sql_dinamis = ( SELECT GROUP_CONCAT( DISTINCT CONCAT( 'max( IF(idk = ', idk, ',huruf,null) ) AS A', idk ) ) FROM nilai  );

SET @SQL = CONCAT( 'SELECT mahasiswa.nim, mahasiswa.nama, ', @sql_dinamis, ' 
FROM nilai
JOIN mahasiswa ON nilai.idm = mahasiswa.idm
JOIN matakuliah ON nilai.idk = matakuliah.idk
WHERE matakuliah.semester = 1
GROUP BY nilai.idm' );
PREPARE stmt 
FROM
@SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

错误消息:

FROM nilai
JOIN mahasiswa ON nilai.idm = mahasiswa.idm
JOIN matakuliah ON nilai.idk = matakuliah.idk
WHERE matakuliah.semester = 1
GROUP BY nilai.idm' )
> OK
> Time: 0s


PREPARE stmt 
FROM
@SQL
> 1052 - Column 'idk' in field list is ambiguous
> Time: 0s

帮我解决这个问题。

我的数据库https://irhas.online/test/test2.txt请帮助我。

1 个答案:

答案 0 :(得分:0)

您的查询引用了idk(来自@sql_dinamis部分),但nilaimatakuliah中都有idk个字段,因此SQL不知道你想要哪一个。您需要更改

中的idk
SET @sql_dinamis = ( SELECT GROUP_CONCAT( DISTINCT CONCAT( 'max( IF(idk = ', idk, ',huruf,null) ) AS A', idk ) ) FROM nilai  );

要么是nilai.idk,要么是matakuliah.idk,例如

SET @sql_dinamis = ( SELECT GROUP_CONCAT( DISTINCT CONCAT( 'max( IF(nilai.idk = ', idk, ',huruf,null) ) AS A', idk ) ) FROM nilai  );

这对我有用(见DBFiddle