MySQL 筛选加入

MySQL Filtered Join

这似乎行得通,但是告诉显示值不为零的记录,所有似乎都告诉它不显示值为 NULL 的记录。 (即不在表 B 中的记录)。似乎 0 等于 mysql 中的 NULL。如何获得我想要的结果?

SELECT DISTINCT Name, CategoryID
FROM sockcategory 
LEFT JOIN sockcategoryparentxref ON 
sockcategory.CategoryID = sockcategoryparentxref.Category_ID 
WHERE CategoryParentID !=0;

架构/示例数据

Table sockcategory:

+-----------+------------+
|   Name    | CategoryID |
+-----------+------------+
| Red       |          1 |
| Blue      |          2 |
| Green     |          3 |
| Colors    |          4 |
| Wholesale |          5 |
+-----------+------------+

Table sockcategoryparentxref:

+-------------+------------------+
| Category_ID | CategoryParentID |
+-------------+------------------+
|           1 |                4 |
|           2 |                4 |
|           3 |                4 |
|           4 |                0 |
+-------------+------------------+

期望的输出:

+-----------+------------+
|   Name    | CategoryID |
+-----------+------------+
| Red       |          1 |
| Blue      |          2 |
| Green     |          3 |
| Wholesale |          5 |
+-----------+------------+

我想你是想比较 WHERE CategoryParentID IS NULL 而不是像下面假设 CategoryParentID 属于 sockcategoryparentxref table.

select DISTINCT s.Name,
s.CategoryID 
FROM sockcategory s
LEFT JOIN sockcategoryparentxref so ON 
s.CategoryID = so.Category_ID 
WHERE so.CategoryParentID IS NULL;

如果不是,则考虑将条件移动到 JOIN ON 子句

select DISTINCT s.Name,
s.CategoryID 
FROM sockcategory s
LEFT JOIN sockcategoryparentxref so ON 
s.CategoryID = so.Category_ID 
AND so.CategoryParentID <> 0;

如果我没理解错的话,这就是你要找的:

SELECT DISTINCT `Name`, `CategoryID`
FROM `sockcategory` 
LEFT JOIN `sockcategoryparentxref`
    ON `sockcategory`.`CategoryID` = `sockcategoryparentxref`.`Category_ID`
    AND `CategoryParentID` <> 0;