3

我有一个具有以下结构的产品表。

   ProductID     ProductName     ProductType
   1             Irrigation      1  
   2             Landscape       2  
   3             Sleeving        3  
   4             Planting        4  

现在我需要按产品类型 3、2、4、1 的顺序返回行为此,我使用了 MYSQL FIELD 方法,它可以像这样正常工作

   Select * from product order by FIELD(producttype,3,2,4,1)

这工作正常,

我的问题是,如果产品类型 3 的产品名称为空,那么它应该采用下一个不为空的产品名称,因此在这种情况下,结果顺序应该是 2、4、1、3。

所以第一个条件是记录需要按照产品类型的顺序

Sleeving      3
Landscape     2
Planting      4
Irrigation    1                

但如果产品类型 3 的产品名称为空,则订单需要为

Landscape     2
Planting      4
Irrigation    1
              3

并且产品类型 2 的进一步产品名称为空,则订单需要为

Planting      4
Irrigation    1
              3
              2

从这个结果中,我只需要选择第一条记录。

我希望我清楚我的观点

任何帮助,将不胜感激

4

5 回答 5

1
Select * from product order by  
ISNULL(PRODUCTNAME),FIELD(producttype,3,2,4,1);

小提琴

于 2013-07-22T07:21:22.707 回答
0

应该管用 !

 SELECT * FROM product ORDER BY FIELD(IF(ProductName is null,0,producttype),1,3,2,5)
于 2013-07-22T07:24:21.480 回答
0

This will satisfy the specification:

ORDER BY NULLIF(ProductName,'') IS NULL, FIELD(producttype,3,2,4,1)

The first expression will return a 1 if the ProductName is "empty" (NULL or zero length string'), otherwise it will return 0.

So, this will sort all the non-empty ProductName first, followed by the empty ProductName.

And then, it will sort by the original expresssion.

Note that this approach preserves the originally specified order, when there are two or more (or all) empty ProductName.

(The test for "empty" could be extended to include other cases, for example, using the TRIM() function as well.


The expression

NULLIF(ProductName,'') IS NULL

is shorthand, it's equivalent SQL-92 compliant:

CASE WHEN ProductName = '' OR ProductName IS NULL THEN 1 ELSE 0 END 

(And there are other ways to get the same result.)

于 2013-07-22T07:23:09.843 回答
0

这是一个非常复杂的查询,并且永远不会[引文需要]按您的需要工作,因为它应该标识另一行中的下一个值,该值可以是任何值。视图、函数、旋转和许多连接是可能的,但作为行数,我认为它不能给出结果。

但是,直接回答,YES Order BY with CASE 是可能的

Select * from product order by 
   CASE WHEN productname IS NULL then FIELD(producttype, 2, 4, 1, 3)
   CASE WHEN productname IS NOT NULL THEN FIELD(producttype, 3, 2, 4, 1)

同样,这不是完整的查询,也不是解决方案

如果您的行数有限,您可以像这样链接您的查询

Select * from product order by 
   CASE WHEN productname IS NULL then FIELD(producttype, 2, 4, 1, 3)
   CASE WHEN (SELECT productname n FROM product WHERE producttype = '2') IS NULL THEN FIELD (4, 1, 3, 2)

如您所见,我已修复查询以搜索其中包含“2”作为产品类型的行。您可以通过进行另一个查询并将其作为主查询来了解它们。

同样,它不是必需的,在服务器端处理行会比这更容易。

于 2013-07-22T07:38:34.303 回答
-1

你可以试试这个

Select * from product where ProductName!='' order by FIELD(producttype,3,2,4,1)

于 2013-07-22T07:31:59.963 回答