MySQL过滤加入

时间:2015-10-05 19:50:43

标签: mysql left-join

这似乎可行,但告诉显示其值不为零的记录,所有似乎都告诉它不显示值为NULL的记录。 (即不在tableB中的记录)。在mysql中,似乎0等于NULL。如何获得我正在寻找的结果?

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

架构/样本数据

sockcategory

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

sockcategoryparentxref

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

期望的输出:

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

2 个答案:

答案 0 :(得分:1)

如果我理解正确,这就是你要找的东西:

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

答案 1 :(得分:0)

我认为您的意思是比较WHERE CategoryParentID IS NULL,而不是假设CategoryParentID属于sockcategoryparentxref表。

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;