【问题标题】:Mysql: order by priority in WHERE LIKE ConditionMysql:在 WHERE LIKE 条件下按优先级排序
【发布时间】:2018-05-17 08:45:59
【问题描述】:

我想获得所有符合以下条件的产品 1.产品名称如“装饰” 2. 列出类别名称中的所有产品,例如“装饰”

这是我的 sql 查询

param = "decor"
sql = "SELECT DISTINCT
P.ProductName,P.ProductPrice FROM
Products_Joined AS P LEFT JOIN Categories_Products_Link AS CP ON
P.ProductId = CP.ProductId LEFT JOIN Categories ON CP.CategoryID =
Categories.CategoryID where P.ProductName LIKE '%" & param &"%' OR
Categories.CategoryName LIKE '%" & param &"%' order by P.ProductName "

我的查询工作正常,我返回了这样的输出

但我希望结果为

需要按产品名称订购

我该怎么做?

【问题讨论】:

  • 您的查询与您向我们展示的当前输出远程不匹配。请向我们展示实际的查询/结果。
  • 更新问题
  • 这个排序背后的逻辑是什么?我猜你想将3-Drawer Chest 排序为Drawer Chest,没有前导数字和破折号。还有其他类型的数据需要特殊的排序规则吗?
  • 不,我的搜索词是“装饰”。我想显示以decor开头的产品名称。

标签: mysql left-join sql-order-by sql-like


【解决方案1】:

请创建一个函数

 DROP FUNCTION IF EXISTS PatIndex;
 DELIMITER $$

 CREATE FUNCTION PatIndex(pattern VARCHAR(255), tblString VARCHAR(255)) 
 RETURNS INTEGER
DETERMINISTIC
BEGIN

DECLARE i INTEGER;
SET i = 1;

myloop: WHILE (i <= LENGTH(tblString)) DO

    IF SUBSTRING(tblString, i, 1) REGEXP pattern THEN
        RETURN(i);
        LEAVE myloop;        
    END IF;    

    SET i = i + 1;

   END WHILE; 

   RETURN(0);

   END

然后将其用作您的排序逻辑

 SELECT DISTINCT
P.ProductName,P.ProductPrice FROM
Products_Joined AS P LEFT JOIN Categories_Products_Link AS CP ON
P.ProductId = CP.ProductId LEFT JOIN Categories ON CP.CategoryID =
Categories.CategoryID where P.ProductName LIKE '%" & param &"%' OR
Categories.CategoryName LIKE '%" & param &"%'                           
 order by   SUBSTRING(P.ProductName ,PATINDEX('[A-z]',P.ProductName ),length(P.ProductName ) - PATINDEX('[A-z]',P.ProductName )+1)

【讨论】:

  • 不,我已经在mysql中执行了这个子字符串查询,patindex也存在于ms sql server中。
【解决方案2】:

试试这个ORDER BY 子句:

ORDER BY
    CASE WHEN P.ProductName LIKE 'Decor%' THEN 0 ELSE 1 END,
    P.ProductName;

这会将名称以Decor 开头的所有产品放在首位,然后是所有其他产品。在这两组中,我们继续按整个产品名称的字母顺序排序。

我可以提供以下完整查询:

SELECT
    t.ProductName, t.ProductPrice
FROM
(
    SELECT DISTINCT
        p.ProductName, p.ProductPrice
    FROM Products_Joined AS P
    LEFT JOIN Categories_Products_Link AS cp
        ON p.ProductId = cp.ProductId
    LEFT JOIN Categories c
        ON cp.CategoryID = c.CategoryID
    WHERE
        p.ProductName LIKE '%param%' OR
        c.CategoryName LIKE '%param%'
) t
ORDER BY
    CASE WHEN t.ProductName LIKE 'Decor%' THEN 0 ELSE 1 END,
    t.ProductName;

【讨论】:

  • 返回空行
  • @JancyAbraham 不可能。 ORDER BY 子句不会影响结果集,只会影响行的顺序。您的查询还有其他问题。只需完全删除ORDER BY,您仍然会得到零行。
  • 当我删除 ORDER BY 子句时,我得到了 4 行。 ORDER BY P.ProductName 有效
  • 您需要使这个问题可重现。如前所述,ORDER BY 无法控制结果集中的行数
  • 当我删除 DISTINCT 时,ORDER BY CASE 起作用了。
猜你喜欢
  • 1970-01-01
  • 2011-10-09
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
相关资源
最近更新 更多