嗨,我尝试创建查询并将其添加,查询错误:

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,请帮助我。

最佳答案

您的查询具有对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.idkmatakuliah.idk

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


这对我有用(请参见DBFiddle

10-04 12:14