【问题标题】:return only last inserted parent id on childs table of multiple duplicate parents ids仅返回多个重复父 ID 的子表上最后插入的父 ID
【发布时间】:2021-08-06 01:03:14
【问题描述】:

我正在尝试在 childs 表上获取最后插入的父母 id 的值,然后加入 祖父母表以获取财产及其总数。

这是我的表结构:

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

我尝试了这个查询,但返回/包括导致 整个祖父母表的总数

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 

【问题讨论】:

  • 你的mysql版本是多少?
  • 你好,我用的是mysqlnd 7.4.5

标签: mysql sql greatest-n-per-group


【解决方案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

【讨论】:

  • 非常感谢!这个解决方案很好@D-Shih
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多