在连接条件中添加通配符

时间:2012-10-13 18:01:35

标签: mysql select join wildcard sql-like

如何将通配符%添加到“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
    

EDIT2

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;
}

1 个答案:

答案 0 :(得分:3)

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,因此,如果您认为specificationssn可能为NULL,则必须处理此特殊用例。

干杯。