GROUP BY中使用的传入参数还是returns1行?
Passed-in parameter used in GROUP BY still returns 1 row?
我偶然发现了这种行为,现在我很好奇到底发生了什么。如果我尝试将参数绑定到 GROUP BY 子句中的列名,数据实际上是 returned,但 只有一行 。 我知道您 not allowed to 使用 table 或列名作为参数,但我想知道是什么导致了这种情况在幕后发生。这深埋在我的(业余)代码中,很难排除故障,因为它没有抛出错误,而且它实际上 returned 数据。我希望对此有更多的了解!
样本table:
| artist | album | label |
|-----------------|----------------|-------------|
| John Coltrane | A Love Supreme | MCA Records |
| John McLaughlin | Extrapolation | Marmalade |
| John Coltrane | A Love Supreme | Impulse! |
| John McLaughlin | Extrapolation | Polydor |
示例代码:
$field = 'artist';
$artist = '%john%';
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY :field';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':artist', $artist);
$stmt->bindParam(':field', $field);
$stmt->execute();
echo 'Row count: '. $stmt->rowCount();
这return秒:"Row count: 1"
我注意到了:
- 改为使用 "GROUP BY artist",并注释掉 :field 的 bindParam 行,我得到了预期的 "Row count: 2"。 这是正确的做法。
- 在 WHERE 子句中使用参数 :field 作为列名(例如 "WHERE :field LIKE :artist")可以得到 "Row count: 0".
所以我想知道的是:
- SQL/PDO 在导致 1 行得到 returned 的场景背后做了什么?
- 如果不支持 GROUP BY 中的参数,为什么不 return 什么都不支持,或者更好的是,抛出错误?我假设不是,但是将参数传递给 GROUP BY 有任何合法用途吗?
当你传递 :field
时,你传递的是一个字符串值。所以,结果是 group by <constant>
,其中 returns 一行。
您不能参数化列名,因此您必须将其直接放入 SQL 语句中:
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY '.$field'
:artist
很好,因为它是一个值,而不是 SQL.
中的标识符
我偶然发现了这种行为,现在我很好奇到底发生了什么。如果我尝试将参数绑定到 GROUP BY 子句中的列名,数据实际上是 returned,但 只有一行 。 我知道您 not allowed to 使用 table 或列名作为参数,但我想知道是什么导致了这种情况在幕后发生。这深埋在我的(业余)代码中,很难排除故障,因为它没有抛出错误,而且它实际上 returned 数据。我希望对此有更多的了解!
样本table:
| artist | album | label |
|-----------------|----------------|-------------|
| John Coltrane | A Love Supreme | MCA Records |
| John McLaughlin | Extrapolation | Marmalade |
| John Coltrane | A Love Supreme | Impulse! |
| John McLaughlin | Extrapolation | Polydor |
示例代码:
$field = 'artist';
$artist = '%john%';
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY :field';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':artist', $artist);
$stmt->bindParam(':field', $field);
$stmt->execute();
echo 'Row count: '. $stmt->rowCount();
这return秒:"Row count: 1"
我注意到了:
- 改为使用 "GROUP BY artist",并注释掉 :field 的 bindParam 行,我得到了预期的 "Row count: 2"。 这是正确的做法。
- 在 WHERE 子句中使用参数 :field 作为列名(例如 "WHERE :field LIKE :artist")可以得到 "Row count: 0".
所以我想知道的是:
- SQL/PDO 在导致 1 行得到 returned 的场景背后做了什么?
- 如果不支持 GROUP BY 中的参数,为什么不 return 什么都不支持,或者更好的是,抛出错误?我假设不是,但是将参数传递给 GROUP BY 有任何合法用途吗?
当你传递 :field
时,你传递的是一个字符串值。所以,结果是 group by <constant>
,其中 returns 一行。
您不能参数化列名,因此您必须将其直接放入 SQL 语句中:
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY '.$field'
:artist
很好,因为它是一个值,而不是 SQL.