0

嘿伙计们,我正在尝试将两个查询合并在一起,但遇到了问题,也许您可​​以看一下,我有这两个单独的查询,我正在尝试合并。第三个连接将在那里获得一个字段,该字段将计算它还有多少父母,而我还没有开始。

SELECT
    e.baseName AS baseName, 
    s.baseName AS masterName
FROM dataSet e 
INNER JOIN dataSet s 
    ON s.id = e.entityId 
ORDER BY e.entityId

SELECT  
    e.baseName AS baseName, 
    b.baseName AS masterName, 
    COUNT(*)-1 AS siblingCount 
FROM dataSet e 
JOIN dataSet b 
    ON b.id=e.entityId 
GROUP BY b.id, b.baseName 

我想出了这个,但遇到了问题

SELECT
    e.baseName AS baseName, 
    s.baseName AS masterName,
    COUNT(*)-1 AS siblingCount 
FROM dataSet e 
    JOIN dataSet b ON b.id = e.entityId
    INNER JOIN dataSet s ON s.id = e.entityId 
GROUP BY b.id, b.baseName 
ORDER BY e.entityId

表结构是这样的

+----+--------------------+----------+
| id | baseName           | entityId |
+----+--------------------+----------+
|  1 | 000000000000000001 |        1 |
|  2 | 000000000000000002 |        1 |
|  3 | 000000000000000003 |        1 |
|  4 | 000000000000000004 |        2 |
|  5 | 000000000000000005 |        2 |
|  6 | 000000000000000006 |        2 |
|  7 | 000000000000000007 |        2 |
|  8 | 000000000000000008 |        2 |
|  9 | 000000000000000009 |        3 |
| 10 | 000000000000000010 |        3 |
| 11 | 000000000000000011 |        3 |
| 12 | 000000000000000012 |        3 |
| 13 | 000000000000000013 |        3 |
| 14 | 000000000000000014 |        3 |
| 15 | 000000000000000015 |        3 |
| 16 | 000000000000000016 |        4 |
| 17 | 000000000000000017 |        4 |
| 18 | 000000000000000018 |        4 |
| 19 | 000000000000000019 |        4 |
| 20 | 000000000000000020 |        4 |
+----+--------------------+----------+

我真正想要的是这个

+--------------------+--------------------+--------------+-------------+
|      baseName      |      masterName    | siblingCount | parentCount | 
+--------------------+--------------------+--------------+-------------+
| 000000000000000001 | 000000000000000001 |          999 |           0 |
| 000000000000000002 | 000000000000000001 |          998 |           1 |
| 000000000000000003 | 000000000000000001 |          998 |           1 |
| 000000000000000004 | 000000000000000002 |          997 |           2 |
| 000000000000000005 | 000000000000000002 |          997 |           2 |
| ....               | ....               |         .... |        .... |
+--------------------+--------------------+--------------+-------------+

帮助将不胜感激

4

1 回答 1

0

好的,所以我最大的障碍就是理解你的数据,但我想我是在“工作”/“树”类比之后得到的。下面是一个 SQL 查询,我认为它会得到你想要的输出。还有一个sqlfiddle ,里面有我用来给你玩的测试数据。希望这可以帮助。

SELECT
    e.baseName AS baseName, 
    s.baseName AS masterName,
    (SELECT COUNT(id) FROM dataSet WHERE entityId < e.entityId) as parentCount,
    (SELECT COUNT(id) FROM dataSet WHERE entityId > e.entityId) as siblingCount
  FROM 
    dataSet e 
    LEFT JOIN dataSet s ON s.id = e.entityId
  ORDER BY 
    e.entityId

祝你好运!

于 2013-01-22T16:49:49.940 回答