Search code examples
coldfusioncoldfusion-10

Move a row to the beginning of a query


I have a recordset of messages, some of which are are from a group named "ADMIN". I want all the messages from the "ADMINS" placed at the top of the query object but I can't re-order them within the original query -- I have to do it after I already have the query object. I have a way to see which rows are from "ADMINS" but I'm not sure the best way to extract them from the query object and put them at the top.

<!--- this is the query object of all the messages --->
<cfset messageData = application.message.getMessages(inboxID)>

<!--- this returns a list of which users inside the recordset are ADMINS --->
<cfset getAdmins = application.message.getAdmins(valueList(messageData.useridfk)) />

Now I want to take all the UserIDs returned in #getAdmins#, remove the messages that are theirs in #messageData# and put them at the top of #messageData# so I can output the results. Is this a QoQ or is there a better way?

I can't really get my head around the QoQ, but I'm taking a stab at it. IS there a better way then doing THREE different QoQs?

<!--- this gets all the rows from Admins --->
<cfquery name="getAdminAnswers" dbtype="query">
    SELECT *
    FROM messageData
    WHERE useridfk in ('#getAdmins.id#')
    ORDER BY UpvotesNum DESC, posted DESC
</cfquery>

<!--- this gets all the rows from non-RDs --->
<cfquery name="getNonAdminAnswers" dbtype="query">
    SELECT *
    FROM messageData
    WHERE useridfk NOT IN ('#getAdmins.id#')
    ORDER BY UpvotesNum DESC, posted DESC
</cfquery>

<!--- join the queries with a UNION in a QoQ --->
<cfquery dbtype="query" name="data">
     SELECT * FROM getAdminAnswers
     UNION 
     SELECT * FROM getNonAdminAnswers
</cfquery>

Answer:

Got it: Like this:

<!--- this combines two queries into one --->
<cfquery name="data" dbtype="query">
   SELECT *, 1 sortCol
   FROM messageData
   WHERE useridfk in ('#variables.getAdmins.id#')
    UNION
   SELECT *, 2 sortCol
   FROM messageData
   WHERE useridfk NOT IN ('#variables.getAdmins.id#')
   ORDER BY sortCol, UpvotesNum DESC, posted DESC
</cfquery>

Solution

  • I can't see that there's a more expedient way of doing this without using QoQ, no. It's kinda what it's for: these exceptional circumstances where the app needs both the original data as from the DB, and a variation of it as well.