2015-10-30 17 views
0

僅當來自表格的文本模式未顯示在產品名稱中時才試圖顯示查詢結果。Mysql:顯示不包含來自其他表格的文本模式的查詢結果

+-----------------------------------------+   +--------+ 
|    Product Name    |   |pattern | 
+-----------------------------------------+   +--------+ 
|Gangster Barbie with guns & accessories |   | Gun | 
|Very Safe Playdoh      |   | Drug |   
|Star Wars Lego       |   | nam | 
|Transformers Decepticon Druglord   |   |  | 
|GTA: Namcat Version      |   |  | 
+-----------------------------------------+   +--------+ 

想有結果:

+-----------------------------------------+ 
|    Product Name    | 
+-----------------------------------------+ 
|Very Safe Playdoh      | 
|Star Wars Lego       | 
+-----------------------------------------+ 

我已經試過LIKE或INSTR如:

select `Product_Name` 
from Product_table 
where NOT LIKE '%'+(select `text_pattern`.`Keywords` from `text_pattern`)+'%'; 

但沒有一個似乎正常工作。有人能幫助或指出正確的方向嗎?

回答

1

下面是使用not exists一個方法:

select p.* 
from product p 
where not exists (select 1 
        from patterns pat 
        where p.name like concat('%', pat.pattern, '%') 
       ); 

注:MySQL不使用+字符串連接。它使用concat()函數。

0
E.g. 

DROP TABLE IF EXISTS product; 

CREATE TABLE product 
(name    VARCHAR(50) NOT NULL PRIMARY KEY); 

INSERT INTO product VALUES 
('Gangster Barbie with guns & accessories'), 
('Very Safe Playdoh'), 
('Star Wars Lego'), 
('Transformers Decepticon Druglord'), 
('GTA: Namcat Version'); 

DROP TABLE IF EXISTS patterns; 

CREATE TABLE patterns 
(pattern VARCHAR(12) PRIMARY KEY); 

INSERT INTO patterns VALUES 
('Gun'),('Drug'),('nam'); 

SELECT * FROM product a LEFT JOIN patterns b ON a.name LIKE CONCAT('%',b.pattern,'%'); 
+-----------------------------------------+---------+ 
| name         | pattern | 
+-----------------------------------------+---------+ 
| Gangster Barbie with guns & accessories | Gun  | 
| GTA: Namcat Version      | nam  | 
| Star Wars Lego       | NULL | 
| Transformers Decepticon Druglord  | Drug | 
| Very Safe Playdoh      | NULL | 
+-----------------------------------------+---------+