这似乎可行,但告诉显示其值不为零的记录,所有似乎都告诉它不显示值为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 |
+-----------+------------+
答案 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;