Postgresql 在使用变量时忽略 ORDER BY,当变量值被硬编码时给出正确的结果

问题描述 投票:0回答:1

以下查询返回按 id 排序的行,即使 sortType 变量值为“e.name”(在控制台中确认)

export async function fetchAnimalList(sortType) {
  noStore();

  try {
    const areas = await sql<Animals>`
    SELECT e.id, e.name, e.slug, e.sliderarray, e.location, e.classification1, a.name AS locationname
    FROM animals e
    JOIN areas a ON (e.location = a.displayorder)
    ORDER BY ${sortType}
  `;
    return areas.rows;
  } 
}

传递变量的函数如下所示:

const animalList = await fetchAnimalList('e.name');

将 ${sortType} 替换为手动编写的 e.name 将返回按预期按 e.name 排序的行。

可能是什么问题?

sql postgresql
1个回答
0
投票

您尝试使用参数代替标识符(列名),但这是行不通的。相反,您的变量被替换为字符串常量,因此实际语句变为:

SELECT ... ORDER BY 'e.name'

按常量排序没有效果。

© www.soinside.com 2019 - 2024. All rights reserved.