How to specify the parent query field from within a subquery in MySQL?(如何在 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";
这篇关于如何在 MySQL 的子查询中指定父查询字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MySQL 的子查询中指定父查询字段?
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01