选择自我加入关系中没有子女的父母

时间:2012-10-22 13:45:13

标签: sql ms-access self-join

我有一个简单的类别名称表,它与category_parent = id有关。我需要选择没有孩子的记录。

从其他答案中我拼凑了这句话:

SELECT cat.category_name AS 'Child Name', cat.id AS 'Child ID',
cat.category_parent AS 'Childs Parent', cat_par.category_name AS 'Parent Name', 
cat_par.id AS 'Parent ID'
FROM category AS cat
LEFT JOIN category AS cat_par ON cat.category_parent = cat_par.id
WHERE cat_par.id IS NULL;

这将成功选择没有PARENT的记录。我尝试将最后一个子句更改为WHERE cat.category_parent IS NULL,但这产生了一个空的。

我也根据另一个答案尝试了这个陈述:

SELECT cat.category_name AS 'Child Name', cat.id AS 'Child ID', 
cat.category_parent AS 'Childs Parent' cat_par.category_name AS 'Parent Name', 
cat_par.id AS 'Parent ID'
FROM category AS cat
WHERE NOT EXISTS 
(SELECT id FROM category AS cat_par WHERE cat.category_parent = cat_par.id);

返回错误No value given for one or more required parameters.

4 个答案:

答案 0 :(得分:2)

Select p.id, p.category_name
From category As p
Where Not Exists (
  Select 'x' 
  From Category c 
  Where c.category_parent = p.id
)

答案 1 :(得分:1)

我认为我理解这种关系已经足够了。怎么样?

SELECT cat.*
FROM category cat
WHERE cat.id not in (
   SELECT distinct category_parent FROM category
);

答案 2 :(得分:0)

第二个查询的问题是您尝试在结果集中包含cat_par.category_name,即使它不在您的FROM子句中。您无法从EXISTS子查询中的表中返回列。

你想要以下内容:

SELECT 
    cat.category_name AS 'Child Name', 
    cat.id AS 'Child ID', 
    cat.category_parent AS 'Childs Parent',
    cat_par.category_name AS 'Parent Name',
    cat_par.id AS 'Parent ID'
FROM 
    category AS cat
    LEFT JOIN category AS cat_par ON cat.category_parent = cat_par.id
WHERE 
    NOT EXISTS 
    (SELECT 
        NULL 
    FROM 
        category AS cat_childless 
    WHERE cat.id = cat_childless.category_parent);

答案 3 :(得分:0)

如果你只需要没有孩子的记录的id和类别名称,这也有效:

SELECT
  category.id,
  category.category_name
FROM
  category LEFT JOIN category AS category_1
    ON category.id = category_1.category_parent
WHERE
  category_1.category_parent IS NULL

我觉得这个查询很好看。但如果你还需要父母的名字,你可以使用:

SELECT
  category.id,
  category.category_name,
  category_1.category_name
FROM
  (category LEFT JOIN category AS category_2
    ON category.id = category_2.category_parent)
  LEFT JOIN category AS category_1
    ON category.category_parent = category_1.ID
WHERE
  category_2.category_parent Is Null;

是的,它变得有点复杂:它只是一个很好的SQL练习,但我宁愿使用Exists版本。