return 仅在多个重复 parent 的孩子 table 上最后插入 parent id
return only last inserted parent id on childs table of multiple duplicate parents ids
我正在尝试获取孩子 table 上最后插入的 parents id 的值,然后加入
grandparents table 得到 属性 和它们的总数。
这是我的 table 结构:
parents
+------------
|pid | item |
+----+------+
| 1 | ite1 |
| 2 | ite2 |
+-----------+
childs
+-------------+
| cid | pid |
+------+------+
| 1 | 1 | -- not
| 2 | 1 | ---- row to be selected(last inserted to join grandparents)
| 3 | 2 | -- not
| 4 | 2 | ---- row to be selected(last inserted to join grandparents)
+-------------+
grandparents
+----------------------+
| gid | cid | property |
+-----+-----+----------+
| 1 | 1 | 1200 |
| 2 | 1 | 1500 |
| 3 | 2 | 101 |
| 4 | 2 | 303 |
| 5 | 3 | 600 |
| 6 | 3 | 10 |
| 7 | 4 | 335 |
| 8 | 4 | 250 |
+----------------------+
结果
+----------------------------+
| item | cid | property |
+--------+------+------------+
| ite1 | 2 | 101 |
| ite1 | 2 | 303 |
| ite1 | 4 | 335 |
| ite1 | 4 | 250 |
+----------------------------+
Total property results : sum(101 + 303 +335 + 250) = 989
我试过这个查询,但 return/ 包括导致的行(与孩子上显示的不同)
总grandparentstable
query:
SELECT g.property from grandparents g
join childs c on g.cid = c.cid
join parents p on c.pid = p.pid
where c.pid in (select DISTINCT pid from childs) and c.pid = 1
您可以尝试使用子查询来获取 MAX(cid)
然后通过子查询的 cid
执行 JOIN
SELECT g.property
from grandparents g
join (
SELECT pid ,MAX(cid) cid
FROM childs
GROUP BY pid
) c on g.cid = c.cid
join parents p on c.pid = p.pid
我正在尝试获取孩子 table 上最后插入的 parents id 的值,然后加入 grandparents table 得到 属性 和它们的总数。
这是我的 table 结构:
parents
+------------
|pid | item |
+----+------+
| 1 | ite1 |
| 2 | ite2 |
+-----------+
childs
+-------------+
| cid | pid |
+------+------+
| 1 | 1 | -- not
| 2 | 1 | ---- row to be selected(last inserted to join grandparents)
| 3 | 2 | -- not
| 4 | 2 | ---- row to be selected(last inserted to join grandparents)
+-------------+
grandparents
+----------------------+
| gid | cid | property |
+-----+-----+----------+
| 1 | 1 | 1200 |
| 2 | 1 | 1500 |
| 3 | 2 | 101 |
| 4 | 2 | 303 |
| 5 | 3 | 600 |
| 6 | 3 | 10 |
| 7 | 4 | 335 |
| 8 | 4 | 250 |
+----------------------+
结果
+----------------------------+
| item | cid | property |
+--------+------+------------+
| ite1 | 2 | 101 |
| ite1 | 2 | 303 |
| ite1 | 4 | 335 |
| ite1 | 4 | 250 |
+----------------------------+
Total property results : sum(101 + 303 +335 + 250) = 989
我试过这个查询,但 return/ 包括导致的行(与孩子上显示的不同) 总grandparentstable
query:
SELECT g.property from grandparents g
join childs c on g.cid = c.cid
join parents p on c.pid = p.pid
where c.pid in (select DISTINCT pid from childs) and c.pid = 1
您可以尝试使用子查询来获取 MAX(cid)
然后通过子查询的 cid
JOIN
SELECT g.property
from grandparents g
join (
SELECT pid ,MAX(cid) cid
FROM childs
GROUP BY pid
) c on g.cid = c.cid
join parents p on c.pid = p.pid