MySql从不同的表中获取匹配的名称

时间:2014-12-24 09:46:17

标签: mysql sql select join left-join

我有4个不同的表,名为

ps_product
ps_product_lang
ps_category_lang
ps_manufacturer

ps_product的表格就像这样

id_product  id_manufacture  id_category_default
1           1               5
2           1               7
3           1               9
4           1               10
5           1               11
6           1               11

ps_product_lang就像这样

id_product   name 
1           Faded Short Sleeve T-shirts
2           Blouse
3           Printed Dress
4           Printed Dress
5           Printed Summer Dress
6           Printed Summer Dress
7           Printed Chiffon Dress

ps_category_lang就像这样

id_category  name
1            paints
2            Home
3            Women
4            Tops
5            T-shirts
6            Tops
7            Blouses

ps_manufacturer表就像这样

id_manufacturer  name
1                Fashion Manufacturer

现在我想要的是当我选择名称时,它会显示这些名称的数据。就像我 将搜索'paint%'之类的东西,然后它应显示产品名称,产品类别和制造商名称的匹配名称 那么有人可以告诉我如何加入这些表来获取值吗?任何帮助和建议都将是非常令人难以置信的。感谢

3 个答案:

答案 0 :(得分:1)

在所有四个表上尝试内部联接,然后在所有名称字段之间执行“和”,如果您希望字段在这三个表中的任何一个中开始说漆,那么:

SELECT *
FROM ps_product pp INNER JOIN ps_product_lang ppl  ON pp.id_product          = ppl.id_product
                   INNER JOIN ps_category_lang pcl ON pp.id_category_default = pcl.id_category
                   INNER JOIN ps_manufacturer pm   ON pp.id_manufacturer     = pm.id_manufacturer
WHERE ppl.name like 'paint%'
AND   pcl.name like 'paint%'
AND   pm.name  like 'paint%'

注意:如果要搜索涂料以存在于这三个表中的任何一个中,则在条件之间使用“OR”而不是“AND”。

答案 1 :(得分:0)

试试这个:

SELECT pl.name, cl.name, m.name
FROM ps_product p 
LEFT OUTER JOIN ps_product_lang pl ON p.id_product = pl.id_product AND pl.name LIKE 'paint%'
LEFT OUTER JOIN ps_category_lang cl ON p.id_category_default = cl.id_category AND cl.name LIKE 'paint%'
LEFT OUTER JOIN ps_manufacturer m ON p.id_manufacture = m.id_manufacture AND m.name LIKE 'paint%'
WHERE pl.id_product IS NOT NULL OR 
      cl.id_category IS NOT NULL OR 
      m.id_manufacture IS NOT NULL;

SELECT pl.name, cl.name, m.name 
FROM ps_product p 
INNER JOIN ps_product_lang pl ON p.id_product = pl.id_product 
INNER JOIN ps_category_lang cl ON p.id_category_default = cl.id_category 
INNER JOIN ps_manufacturer m ON p.id_manufacture = m.id_manufacture 
WHERE pl.name LIKE 'paint%' OR 
      cl.name LIKE 'paint%' OR 
      m.name LIKE 'paint%';

答案 2 :(得分:0)

 SELECT x.id,y.name,z.name,a.name 
 FROM ps_product x 
 FULL OUTER JOIN ps_product_lang y 
 ON x.id_product = y.id_product 
 FULL OUTER JOIN ps_category_lang z
 ON x.id_category_default = z.id_category 
 FULL OUTER JOIN ps_manufacturer a 
 ON x.id_manufacture = a.id_manufacture 
 WHERE a.name LIKE 'paint%'
 OR y.name LIKE 'paint%'
 OR z.name LIKE 'paint%'
此处需要

全外联接,因为您希望匹配所有名称,以便获取所有数据并与模式匹配' paint%'并显示匹配的行。尝试一次