MySQL用于搜索的正则表达式

时间:2016-06-17 06:59:03

标签: mysql null substring

我在MySQL中有两个表,一个是产品,另一个是排除。我必须选择表products中不存在于表exclusions中的所有产品。当通过"直接"进行排除时,我取得了成功。字段等价,即产品的参考代码。

但许多产品可以通过模式排除。它由参考代码的最后3位数字组成。因此,如果我有值" ++ 6",则表示该序列的第三个数字,即参考代码的最后一个数字,必须与6不同。如果是6,那么该产品被排除在外。我在这里被卡住了。我应该使用什么正则表达式? 该模式可以完全是' 0 + 6',' 036'等。

我粘贴示例表的结构和数据,以及与引用一起使用的SELECT。问题是改变SELECT以包括那些可以解释"模式"的正则表达式(或其他)。

 CREATE TABLE IF NOT EXISTS `exclusions` (
   `id_exclusions` int(11) NOT NULL AUTO_INCREMENT,
   `reference` varchar(10) NOT NULL,
   `pattern` varchar(3) NOT NULL,
   PRIMARY KEY (`id_exclusions`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

 INSERT INTO `exclusions` (`id_exclusions`, `reference`, `pattern`) VALUES
 (1, '8036', ''),
 (2, '', '++5');

  CREATE TABLE IF NOT EXISTS `products` (
   `id_products` int(11) NOT NULL AUTO_INCREMENT,
    `reference` varchar(10) NOT NULL,
   PRIMARY KEY (`id_products`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

 INSERT INTO `products` (`id_products`, `reference`) VALUES
     (1, '8034'),
     (2, '8035'),
      (3, '8036');

现在SELECT代码正在运行

SELECT * FROM products AS p LEFT JOIN exclusions AS e ON p.reference = e.reference WHERE e.reference IS NULL

结果:

  id_products, reference, id_exclusions, reference, pattern
  1, 8034, NULL, NULL, NULL
  2, 8035, NULL, NULL, NULL

使用更正后的SELECT,它应该只返回

  id_products, reference, id_exclusions, reference, pattern
  1, 8034, NULL, NULL, NULL

作为' xx5'参考代码被排除在外。

1 个答案:

答案 0 :(得分:1)

最后,SQL非常简单:

 SELECT * FROM products AS p WHERE id_products NOT IN
 (SELECT id_products FROM exclusions AS e LEFT JOIN
  products AS p ON p.reference = e.reference WHERE p.id_products IS NOT NULL)
 AND id_products NOT IN
 (SELECT id_products FROM exclusions AS e LEFT JOIN
 products AS p ON SUBSTRING(p.reference, -3)
 LIKE REPLACE(pattern, '+', '%')
 WHERE id_products IS NOT NULL) ORDER BY p.reference ASC
相关问题