简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM