简体   繁体   中英

Get Minimum data id When using JOIN

I have Table Structure as below在此处输入图片说明

And My Query is as below

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'

This query is working quite fine but my requirement is I need an id which have minRnode As given in query in output ..

What i have tried

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

But this returns an error maybe for duplicate of id.

This is my live code In Sql Fiddle.

My output for First Woking query is

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

So as per this output i need an id from table Which have minRnode(Monimum Rnode) = 6

Here is the solution for your problem:

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')

Link to the demo:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM