按特定顺序从数据库中获取数据

时间:2015-06-11 04:39:30

标签: mysql sql database mysqli

我有一个名为vendor的表,这里是一个视图

id  vendorname   staffpick   totalfav
1      V1           yes        1
2      V2           yes        3
3      V3           yes        4
4      V4                      2
5      V5                      5
6      D
7      A

我希望按以下顺序创建供应商列表(不重复供应商) 首先,这些供应商应该来到,其员工薪资的价值是肯定的,并且这些员工挑选的供应商应该按照总价值的十分顺序排列。 然后那些供应商应该来到谁有totfav但是staffpick值不是肯定的。 最后一部分是显示那些既不是stafffick也不是totalfav的供应商,这些供应商应按字母顺序排列

列表应该是这样的

V3
V2
V1
V5
V4
A
D

如果我尝试为这样的每个部分创建一个数组,我会得到重复

$sql = "SELECT * FROM  vendors where staffpick='yes' and favvendor!=''";
$result = mysql_query($sql);
$row = mysql_fetch_array($result)

任何人都可以告诉我如何进行排序

3 个答案:

答案 0 :(得分:1)

尝试这样的事情

<cfset var qryFoodRequest = queryNew("")>       
<cfset var localData = structNew()>

<cfif (structKeyExists(Form,"Fromdatepicker") AND isDate(Form.Fromdatepicker) ) 
      AND (structKeyExists(Form,"Todatepicker") AND isDate(Form.Todatepicker) )>
    <cfset localData.frmDate = listGetAt(Form.Fromdatepicker,3,'/') & '-' & listGetAt(Form.Fromdatepicker,2,'/') & '-' & listGetAt(Form.Fromdatepicker,1,'/')>
    <cfset localData.toDate = listGetAt(Form.Todatepicker,3,'/') & '-' & listGetAt(Form.Todatepicker,2,'/') & '-' & listGetAt(Form.Todatepicker,1,'/')>
</cfif>


<cfquery name="qryFoodRequest" datasource="ebms"  cachedWithin = "#createTimeSpan(0,0,0,5)#">
    SELECT  e.FullName FullName
            , e.EmployeeCode EmployeeCode
            , e.DesignationName DesignationName
            , e.DateOfJoin DateOfJoin
            , e.DepartmentName DepartmentName
            , e.ManagerName ManagerName
            , e.ParentOffice ParentOffice
            , f.Requesttype Requesttype
            , f.Foodtype Foodtype
            , f.ReqDate ReqDate
            , f.remarks remarks
    FROM    foodrequest f INNER JOIN employeedetails e 
                 ON  f.EmployeeId = e.empId 

    <cfif structKeyExists(localData,"frmDate") AND structKeyExists(localData,"toDate")>
        AND f.ReqDate between ('#localData.frmDate#') and ('#localData.toDate#')
    </cfif>     
    order by e.empId;
</cfquery>          

<cfreturn qryFoodRequest>

答案 1 :(得分:1)

您需要在查询中添加order by子句。查询将是这样的

SELECT * FROM  vendors where staffpick='yes' and favvendor!='' order by totalfav desc;

答案 2 :(得分:1)

尝试sqlserver

SELECT * 
FROM  vendors
ORDER BY case when staffpick ='YES' then totalfav end DESC,
         case when staffpick IS NULL then totalfav end DESC,
         case when staffpick IS NULL AND totalfav IS NULL then vendorname end ASC