简体   繁体   中英

Select MIN value on INNER JOIN

I have some problem when selecting Minimum value. i have create inner join with 2 table and simple calculation in SQL query. Now i want to select minimum value from the calculation. here my query..

 $sql = "SELECT jobmatl_mst.item as item2,jobmatl_mst.u_m, job_mst.item, jobmatl_mst.job, jobmatl_mst.item as item2, jobmatl_mst.description, jobmatl_mst.matl_qty_conv , itemwhse_mst.item  as whseitem,itemwhse_mst.qty_on_hand, itemwhse_mst.qty_on_hand / jobmatl_mst.matl_qty_conv as total 
FROM job_mst 
INNER JOIN jobmatl_mst ON job_mst.job=jobmatl_mst.job 
INNER JOIN itemwhse_mst ON jobmatl_mst.item=itemwhse_mst.item 
WHERE job_mst.item ='601010944003' AND job_mst.type='S'
ORDER BY total";

i want to find minimum value for "total"..

Update: The following solution is specific to MySQL.


The simplest answer that you can get that is close to your own code is to use ORDER BY total LIMIT 1 at the end of your query.

 $sql = " SELECT jobmatl_mst.item as item2, jobmatl_mst.u_m, job_mst.item, jobmatl_mst.job, jobmatl_mst.item as item2, jobmatl_mst.description, jobmatl_mst.matl_qty_conv , itemwhse_mst.item as whseitem, itemwhse_mst.qty_on_hand, itemwhse_mst.qty_on_hand / jobmatl_mst.matl_qty_conv as total FROM job_mst INNER JOIN jobmatl_mst ON job_mst.job=jobmatl_mst.job INNER JOIN itemwhse_mst ON jobmatl_mst.item=itemwhse_mst.item WHERE job_mst.item ='601010944003' AND job_mst.type='S' ORDER BY total # Sort the result in a # way that lowest is first and highest is last LIMIT 1 # Then we need the first value "; 

Usage of aggregate function MIN() and group by is also possible:

 $sql = " SELECT jobmatl_mst.item as item2, jobmatl_mst.u_m, job_mst.item, jobmatl_mst.job, jobmatl_mst.item as item2, jobmatl_mst.description, jobmatl_mst.matl_qty_conv , itemwhse_mst.item as whseitem, itemwhse_mst.qty_on_hand, MIN(itemwhse_mst.qty_on_hand / jobmatl_mst.matl_qty_conv) as min_total FROM job_mst INNER JOIN jobmatl_mst ON job_mst.job=jobmatl_mst.job INNER JOIN itemwhse_mst ON jobmatl_mst.item=itemwhse_mst.item WHERE job_mst.item ='601010944003' AND job_mst.type='S' GROUP BY jobmatl_mst.item as item2, jobmatl_mst.u_m, job_mst.item, jobmatl_mst.job, jobmatl_mst.item as item2, jobmatl_mst.description, jobmatl_mst.matl_qty_conv , itemwhse_mst.item as whseitem, itemwhse_mst.qty_on_hand "; 

Note that in this case all the columns other than the one with aggregate function comes in the GROUP BY clause.

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