MS SQL query within a query ColdFusion environment

时光怂恿深爱的人放手 提交于 2019-12-11 10:50:11

问题


I have 2 tables, one is called Food while the other is FoodCategory. The relation between them is the FoodCatID which contain in both tables.

What I try to archive is displaying:

Meat

  • Chicken
  • Beef

Veg

  • tomatoe
  • potatoe

I assume I will need a query within a query? I first try to use Distinct to get the 2 unique FoodCatID:

Select Distinct FoodCategory.FoodCatID, FoodCategoryName
From Food INNER JOIN FoodCategory ON Food.FoodCatID = FoodCategory.FoodCatID

This will give me the 2 categories, but then how can I use the CatID to run the second part of the query?

I'm using this on a ColdFusion page, should I archive the result using SQL queries or can I do it through CF code?


回答1:


should I archive the result using SQL queries or can I do it through CF code?

Both. Use a single JOIN to retrieve the categories and food names. SQL Fiddle

SELECT fc.FoodCatID
       , fc.FoodCategoryName
       , f.FoodID
       , f.FoodName
FROM   FoodCategory fc INNER JOIN Food f ON f.FoodCatID = fc.FoodCatID
ORDER BY fc.FoodCategoryName, f.FoodName

Then use a "grouped" cfoutput. to list all of the foods - but only display the category headers once.

Note, the results must be ordered by category name first, or it will not work

  <cfoutput query="yourQuery" group="FoodCategoryName">
      <!--- display header once -->
      #FoodCategoryName#<br><br>
      <cfoutput>
         <!--- display all foods --->
          #FoodName#<br>
      </cfoutput>
  </cfoutput>


来源:https://stackoverflow.com/questions/18524431/ms-sql-query-within-a-query-coldfusion-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!