如何在 MySQL 的子查询中指定父查询字段?
如何在 MySQL 的子查询中指定父查询字段?
例如:
我已经用 PHP 编写了一个基本的公告板类型程序.
For Example:
I have written a basic Bulletin Board type program in PHP.
在数据库中,每个帖子都包含:id(PK) 和 parent_id(父帖子的 id).如果帖子本身是父级,则其 parent_id 设置为 0.
In the database each post contains: id(PK) and parent_id(the id of the parent post). If the post is itself a parent, then its parent_id is set to 0.
我正在尝试编写一个 mySQL 查询,该查询将查找每个父帖子以及该父母拥有的孩子的数量.
I am trying to write a mySQL query that will find every parent post and the number of children that the parent has.
$query = "SELECT id, (
SELECT COUNT(1)
FROM post_table
WHERE parent_id = id
) as num_children
FROM post_table
WHERE parent_id = 0";
棘手的部分是第一个 id 不知道它应该引用子查询之外的第二个 id.我知道我可以执行 SELECT id AS id_tmp 然后在子查询中引用它,但是如果我还想返回 id 并保留id".作为列名,那么我必须执行一个查询,返回具有相同数据的 2 列(这对我来说似乎很乱)
The tricky part is that the first id doesn't know that it should be referring to the second id that is outside of the subquery. I know that I can do SELECT id AS id_tmp and then refer to it inside the subquery, but then if I want to also return the id and keep "id" as the column name, then I'd have to do a query that returns me 2 columns with the same data (which seems messy to me)
$query = "SELECT id, id AS id_tmp,
(SELECT COUNT(1)
FROM post_table
WHERE parent_id = id_tmp) as num_children
FROM post_table
WHERE parent_id = 0";
凌乱的方式效果很好,但我觉得有机会在这里学习一些东西,所以我想我会发布这个问题.
The messy way works fine, but I feel an opportunity to learn something here so I thought I'd post the question.
推荐答案
怎么样:
$query = "SELECT p1.id,
(SELECT COUNT(1)
FROM post_table p2
WHERE p2.parent_id = p1.id) as num_children
FROM post_table p1
WHERE p1.parent_id = 0";
或者如果你在 p1.id 上加上一个别名,你可能会说:
or if you put an alias on the p1.id, you might say:
$query = "SELECT p1.id as p1_id,
(SELECT COUNT(1)
FROM post_table p2
WHERE p2.parent_id = p1.id) as num_children
FROM post_table p1
WHERE p1.parent_id = 0";
相关文章