mysql - 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
解决方案
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)
推荐阅读
- python - 在多个环境中使用一个 IPython
- python - 从数据框python散点图多列
- python - 表单未在 Django 类基本视图的 HTML 模板中显示
- arrays - 无法在特定行的索引处打印值。只有在打印 25 的值后,我才会遇到分段错误:11
- mongodb - 猫鼬'populate()'没有填充
- laravel - Laravel 7 cognito 用于网络和应用程序
- javascript - 无法将数组数据添加到 MongoDB 集合
- macos - OSX 汇编问题
- java - HTTP 请求中的 Java 内存泄漏
- python - 遍历列表中的所有元素以查找 Pandas 数据框中的行索引