开发者

SQL, WHERE id=5, but i want a certain record to show up first.

开发者 https://www.devze.com 2023-03-24 01:23 出处:网络
not sure how to do this but say i have a table with a bunch of items owned by userID 5, I want to make it so that if i search for a specific item from that user, all of his items will show up, but the

not sure how to do this but say i have a table with a bunch of items owned by userID 5, I want to make it so that if i search for a specific item from that user, all of his items will show up, but the item searched for will appear first and the rest of the items will follow. For example:

Items table
--------开发者_运维知识库---
itemID       userID    itemName
1              5       Coffee Mug
2              5       iPhone
3              5       LCD Monitor
4              5       Macbook pro
5              5       Shell

So say i do a search for an iPhone, i want my results to return all of userID's items (WHERE userID=5), but... I want the iPhone item to be at the top of the list! Thanks all for your help!

damien


EDIT now we are no longer searching for 'iPhone' we are indicating first item by @ItemID:

ORDER BY 
  CASE WHEN itemID = @ItemID THEN 'a' ELSE 'z' END 
  --, secondary ordering


ORDER BY      
   case when Items.itemID = 2 then 0 else 1 end ASC      
   ,Items.itemName ASC


Create an additional column for the SELECT with a case statement that is 0 when your condition is satisfied and 1 otherwise, and then ORDER BY that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号