【问题标题】:Add wildcard in join condition在连接条件中添加通配符
【发布时间】:2012-10-13 18:01:35
【问题描述】:

如何在“specifications.sn”中添加通配符 %?

SELECT `products2`.`type`, 
       `products2`.`sn`, 
       `products2`.`lap`, 
       `specifications`.`year` 
FROM `products2`
INNER JOIN `specifications` 
      ON `products2`.`sn` LIKE `specifications`.`sn`
WHERE `products2`.`id` = ? LIMIT 1

编辑:

添加了当前查询

  • 删除了反引号
  • 添加了你的 CONCAT

    SELECT products2.type, 
    products2.sn, 
    products2.lap, 
    specifications.year 
    FROM products2
    INNER JOIN specifications 
    ON products2.sn LIKE CONCAT('%', specifications.sn, '%')
    WHERE products2.id = ? LIMIT 1
    

替代查询 - 与上面的代码相同的错误

  • 删除了反引号
  • 删除了 INNER JOIN
  • 在 WHERE 语句中添加 LIKE

    SELECT products2.type, 
    products2.sn, 
    products2.lap, 
    specifications.year
    FROM products2, 
    specifications
    WHERE products2.id = ? AND products2.sn LIKE '%' + specifications.sn + '%' LIMIT 1
    

编辑2

PHP 代码

if ($stmt = $mysqli->prepare('SELECT products2.type, 
products2.sn, 
products2.lap, 
specifications.year 
FROM products2
INNER JOIN specifications 
ON products2.sn LIKE CONCAT('%', specifications.sn, '%')
WHERE products2.id = ? LIMIT 1')) { 

$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($type, $sn, $lap, $year);
$stmt->fetch();

echo $type . '<br/>';
echo $sn . '<br/>';
echo $lap . '<br/>';
echo $year . '<br/>';

$stmt->close();

} else {
echo $mysqli->error;
}

【问题讨论】:

  • 我认为是查询调用方式的问题。如果您将其粘贴到 phpmyadmin 中,它将起作用
  • 你是对的。我该如何解决这个问题?是因为我使用的是准备好的语句吗?
  • 能把php部分也发一下吗?
  • 你必须转义查询中的引号:\'\'
  • 另外,您正在绑定 'i' 参数,而在查询中您使用的是 '?'这正常吗?在第二个注意事项中,请注意您在绑定它之后获得了 $id 的值。我会事先取回它。

标签: mysql select join wildcard sql-like


【解决方案1】:
SELECT `products2`.`type`,
       `products2`.`sn`,
        `products2`.`lap`, `specifications`.`year`
FROM `products2`
INNER JOIN `specifications`
      ON `products2`.`sn` LIKE 
         CONCAT(`specifications`.`sn`, '%')
WHERE `products2`.`id` = ? LIMIT 1

请注意以下几点:

  • 这对于参加表演将非常无效
  • CONCAT(NULL, 'ADADSA') 返回 NULL,因此如果您认为 specifications.sn 可能为 NULL,则必须注意这个特殊用例。

干杯。

【讨论】:

  • 你喜欢 %specifications.sn% 吗?
  • 您可以使用带有任意数量参数的 CONCAT,例如在您的情况下,您确实可以使用 CONCAT('%', specifications.sn, '%')
  • 你注意到它是无效的。您将如何比较两个不同表中的两列?
  • 好吧,这是无效的,但是您可能没有任何其他简单的解决方案来实现您的目标。我不知道你为什么会出现这个错误。
  • 我认为它似乎在尝试除以百分号。
猜你喜欢
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 1970-01-01
  • 2021-08-28
相关资源
最近更新 更多