且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

父母/孩子在同一张桌子

更新时间:2023-02-05 21:53:39

数据库中第一个孩子没有任何意义,您可以通过id的最小值或值的最小值获得第一个孩子,但是这些值未按特定顺序存储在表中,因此您无法确定哪个值是第一个.

There is no meaning of the first child in the database, you can get the first child by the mininum of the id or the minimum of the value, but the values are not stored with a specific order in the table, so you can't tell which value is the first one.

但是,假设id是自动增量列,则第一个子项的值是最小值id的值,那么您可以执行以下操作:

But, assuming that the id is auto incremental column, then value of the first child is the value of the minimum id, then you can do this:

SELECT
  t1.parent,
  t2.name,
  t1.value
FROM tablename AS t1
INNER JOIN
(
  SELECT MIN(id) AS id, parent
  FROM tablename
  GROUP BY parent
) AS t22 ON t22.id = t1.id AND t1.parent = t22.parent
INNER JOIN tablename AS t2 ON t1.parent = t2.id;

在此处查看其运行情况:

See it in action here:

这会给你:

| PARENT | NAME | VALUE |
-------------------------
|      1 |  aaa |   111 |
|      3 |  ccc |   333 |


或:您可以通过最小值获得它:


Or: You can get it by the minimum value:

SELECT
  t1.parent,
  t2.name,
  MIN(t1.value) AS value
FROM tablename AS t1
INNER JOIN tablename AS t2 ON t1.parent = t2.id
GROUP BY t1.parent, t2.name;

查看实际效果:

这将为您提供:

| PARENT | NAME | VALUE |
-------------------------
|      1 |  aaa |   111 |
|      3 |  ccc |   333 |