Search code examples
mysqlselectjoinwildcardsql-like

Add wildcard in join condition


How do I add wildcards % to the "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

EDIT:

Added current query

  • Removed backticks
  • Added your 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
    

Alternative query - Same error like code above

  • Removed backticks
  • Removed INNER JOIN
  • Added LIKE in WHERE statement

    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 code

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

Solution

  • 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
    

    Please note the following:

    • this is going to be highly ineffective regarding to join performances
    • CONCAT(NULL, 'ADADSA') returns NULL, therefore you have to take care of this special use case if you think specifications.sn might be NULL.

    Cheers.