首页 > 解决方案 > MySQL LEFT JOIN 未返回所需结果

问题描述

我有一个我认为是简单的 MySQL 问题,我似乎找不到适用于我正在做的事情的答案。我有两个带有 LEFT JOIN 的表。对于此示例,表 1 将只有 1 行,表 2 将有 3 行。

表 1:inv_info

id  manufacturer    model   description     quantity
1   SP              A55     USB disk        7

表 2:inv_category

id  categories
1   USB
1   Hard disk
1   SSD

这是查询:

SELECT manufacturer, model, description, quantity, categories 
FROM inv_info 
LEFT JOIN inv_category ON inv_info.id=inv_category.id 
WHERE manufacturer LIKE '%usb%' 
   OR model LIKE '%usb%' 
   OR description LIKE '%usb%' 
   OR categories LIKE '%usb%'

如果我的搜索项是类别名称之一,它会返回每个类别项的结果,而不仅仅是我搜索的那个。我希望它搜索此搜索词的所有类别行,但不为 inv_categories 中的每一行返回一行。

我从上述查询中得到的结果:

manufacturer    model   description     quantity    categories
SP              A55     USB disk        7           SATA
SP              A55     USB disk        7           SSD
SP              A55     USB disk        7           usb

我希望它搜索两个表,但只返回表 1 中的 1 行数据,而不是表 2 中每个类别的数据行。

期望的结果:

manufacturer    model   description quantity    categories
SP              A55     USB disk    7           usb

标签: mysql

解决方案


SELECT manufacturer, model, description, quantity, categories 
FROM inv_info 
LEFT JOIN inv_category ON inv_info.id=inv_category.id 
WHERE (    manufacturer LIKE '%usb%' 
        OR model LIKE '%usb%' 
        OR description LIKE '%usb%' )
  AND categories LIKE '%usb%'

UPDATE

This query text implicitly converts LEFT JOIN to INNER JOIN due to the condition by the column from inv_category table in WHERE clause.

So correct query text is

SELECT manufacturer, model, description, quantity, categories 
FROM inv_info 
LEFT JOIN inv_category ON inv_info.id=inv_category.id AND categories LIKE '%usb%'
WHERE (    manufacturer LIKE '%usb%' 
        OR model LIKE '%usb%' 
        OR description LIKE '%usb%' )  

or maybe even

SELECT manufacturer, model, description, quantity, categories 
FROM ( SELECT *
       FROM inv_info 
       WHERE (    manufacturer LIKE '%usb%' 
               OR model LIKE '%usb%' 
               OR description LIKE '%usb%' ) ) models
LEFT JOIN ( SELECT *
            FROM inv_category 
            WHERE categories LIKE '%usb%' ) categories USING (id)

推荐阅读