如何在mySQL中的子查询中指定父查询字段?
有没有一种方法来指定在MySQL中的子查询中的父查询字段?
例如:
我已经用PHP编写了一个基本的公告板types程序。
在数据库中,每个post都包含:id(PK)和parent_id(父post的ID)。 如果该post本身是父亲,则其parent_id设置为0。
我正在尝试编写一个mySQL查询,它将查找每个父级post以及父级拥有的子级数。
$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列与相同的数据(这似乎是凌乱的我)
$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";
混乱的方式运作良好,但我觉得有机会在这里学习一些东西,所以我想我会提出这个问题。
怎么样:
$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上放置一个别名,你可能会说:
$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";
你可以尝试这样的事情
SELECT pt.id, CountTable.Cnt FROM post_table pt LEFT JOIN ( SELECT parent_id, COUNT(1) Cnt FROM post_table WHERE parent_id <> 0 GROUP BY parent_id ) CountTable ON pt.id = CountTable.parent_id WHERE pt.parent_id = 0
为了回到你的例子,在子select中使用主表的别名
SELECT pt.id, (SELECT COUNT(1) FROM post_table WHERE parent_id = pt.id) FROM post_table pt WHERE pt.parent_id = 0
给表独特的名字:
$query = "SELECT a.id, (SELECT COUNT(1) FROM post_table b WHERE parent_id = a.id) as num_children FROM post_table a WHERE a.parent_id = 0";
以下语法在Oracle中工作。 你可以testing,如果相同的作品在MYSQL呢? 在Oracle中称为标量子查询。
如果您使用同一个表两次,您只需要以不同的方式来区分这两个表。
sql> select empno, 2 (select dname from dept where deptno = emp.deptno) dname 3 from emp 4 where empno = 7369; EMPNO DNAME ---------- -------------- 7369 RESEARCH sql> select parent.empno, 2 (select mgr from emp where empno = parent.empno) mgr 3 from emp parent 4 where empno = 7876; EMPNO MGR ---------- ---------- 7876 7788
谢谢唐。 我有一个嵌套的查询,如下所示,其中的WHERE
子句无法确定别名v1
。 这里是不工作的代码:
Select teamid, teamname FROM team as t1 INNER JOIN ( SELECT venue_id, venue_scores, venue_name FROM venue WHERE venue_scores = ( SELECT MAX(venue_scores) FROM venue as v2 WHERE v2.venue_id = v1.venue_id /* this where clause wasn't working */ ) as v1 /* v1 alias already present here */ );
所以,我只是在JOIN
添加了别名v1
。 这使得它工作。
Select teamid, teamname FROM team as t1 INNER JOIN ( SELECT venue_id, venue_scores, venue_name FROM venue as v1 /* added alias v1 here again */ WHERE venue_scores = ( SELECT MAX(venue_scores) FROM venue as v2 WHERE v2.venue_id = v1.venue_id /* Now this works!! */ ) as v1 /* v1 alias already present here */ );
希望这会对某人有所帮助。