Mysql合并查询

时间:2013-01-21 06:45:10

标签: mysql join parent-child treenode

嘿伙计们我正在尝试将两个查询联系在一起并且遇到问题,也许你可以看看,我有两个单独的查询我正试图结合。有一个第三个连接将在那里得到一个字段,将计算它还有多少父母,我还没有开始。

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 |
| ....               | ....               |         .... |        .... |
+--------------------+--------------------+--------------+-------------+

帮助将不胜感激

1 个答案:

答案 0 :(得分: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
祝你好运!