获取最小数据ID使用JOIN时

时间:2018-04-18 09:18:26

标签: mysql sql database join mysqli

我有如下表结构 enter image description here

我的查询如下

SELECT *,MIN(node.rnode) AS minRnode 
FROM final_mlm AS node, 
final_mlm AS parent 
where node.lnode BETWEEN parent.lnode AND parent.rnode AND parent.id = 1 
AND node.placement='l'

此查询工作正常但我的要求是我需要一个minRnode的ID,如输出中的查询中所示..

我尝试了什么

SELECT *, MIN(node.rnode) as minn
FROM (
        SELECT * FROM final_mlm AS node,
        final_mlm AS parent 
        where node.lnode BETWEEN parent.lnode AND parent.rnode 
        AND parent.id = 4 
        AND node.placement='l' 
     ) as t on t.rnode=node.minn

但是这会返回错误,可能是id的重复。

这是我的 live code 在Sql Fiddle。

First Woking查询的输出是

id  sponserid   level   lnode   rnode   placement   id  sponserid   level   lnode   rnode   placement   minRnode
3   2           2       21      22      l           1   0           0       1       24                  6

所以根据这个输出,我需要一个表中的id,其中minRnode(Monimum Rnode)= 6

1 个答案:

答案 0 :(得分:2)

以下是您的问题的解决方案:

SELECT id 
FROM final_mlm
WHERE rnode IN (SELECT MIN(node.rnode)
                FROM final_mlm AS node 
                INNER JOIN final_mlm AS parent 
                ON node.lnode BETWEEN parent.lnode AND parent.rnode
                WHERE parent.id = 1 
                AND node.placement='l')

链接到演示:

  

http://sqlfiddle.com/#!9/29e8d8/59