首页 > 解决方案 > 带有 groupBy 的 MYSQL 子查询并具有 - 检查“child”是否有“cousins”,如果有则过滤掉

问题描述

这是示例数据库,您可以在问题末尾的 mysql fiddle 中看到更详细的数据库:

children:
 id, name, age, date_of_birth, favorite_book, parent_id
parents: 
  id, gender, grandparent_id (nullable)
grandparents: 
  id

我想构建以下查询:

返回所有最喜欢的书,按孩子的出生日期排序,没有祖父母或阿姨的表兄弟姐妹。

这是一个愚蠢的例子:),我知道。

这可以在一个查询中完成吗?

这些方面的东西:

SELECT 
  children.id,
  children.name,
  children.date_of_birth,
  children.favorite_book,
  hasYoungerAuntCousins <-- this is what I don't know how to set up
FROM
  children
ORDER BY
  children.date_of_birth DESC
GROUP BY
  favorite_book
HAVING
 hasYoungerAuntCousins == 0

所以结果会是这样的:

2, Joe, 1/1/2010, Basics 3 of MySQL, 0
9, Moe, 1/1/2005, Basics 1 of MySQL, 0
5, Zoe, 1/1/2001, Basics 2 of MySQL, 0
...

hasYoungerAuntCousins子查询应0在两种情况下返回:

让我知道这是否有意义以及我是否遗漏了什么。

与此同时,我正在寻找解决方案,也感谢评论中的任何指针。

编辑:

这是一个小提琴链接:

http://sqlfiddle.com/#!9/f06d5e

标签: mysqlsubqueryparent-child

解决方案


推荐阅读