1

我有一个简单的类别名称表,它使用 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

4 回答 4

3
Select p.id, p.category_name
From category As p
Where Not Exists (
  Select 'x' 
  From Category c 
  Where c.category_parent = p.id
)
于 2012-10-22T13:51:14.430 回答
2

我想我足够理解这种关系。这个怎么样?

SELECT cat.*
FROM category cat
WHERE cat.id not in (
   SELECT distinct category_parent FROM category
);
于 2012-10-22T13:50:56.637 回答
1

如果您只需要没有子项的记录的 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 版本。

于 2012-10-22T14:29:39.443 回答
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);
于 2012-10-22T13:56:30.280 回答