简体   繁体   English

PDO使用MySql Case对绑定变量进行排序

[英]PDO using MySql Case for ordering with bound variables

I've been researching this and I think I've found the best solution but I'm not 100% sure. 我一直在对此进行研究,我想我已经找到了最佳的解决方案,但我不确定100%。 I have a good handle on PDO but this is the first time I've encountered CASE in mysql. 我对PDO有很好的了解,但这是我第一次在mysql中遇到CASE。 This code is working but I'm wondering if it's efficient? 该代码有效,但我想知道它是否有效? If I were to have multiple keys, I would have to write many arrays to be able to search and order. 如果要有多个键,则必须编写许多数组才能搜索和排序。 Is there a shorter way to write this code or is this the most efficient? 有没有一种较短的方法来编写此代码,或者这是最有效的? Thanks! 谢谢!

$filters = "
    AND (name LIKE :keys
    OR note LIKE :keys
    OR tagnum = :skeys)
";
$order = "
    ORDER BY
        CASE
            WHEN tagnum = :skeys THEN 0
            WHEN name = :skeys THEN 1
            WHEN name LIKE :lkeys THEN 2
            WHEN name LIKE :rkeys THEN 3
            ELSE 4
        END
    ASC
";
$arr[':keys'] = "%$keys%"; // both wild cards
$arr[':skeys'] = $keys; // stripped keys, no wild cards
$arr[':lkeys'] = "$keys%"; // left key, right wild card
$arr[':rkeys'] = "%$keys"; // right key, left wild card

If you want to have complete control over how you order your resultset, then your solution is perfect. 如果您想完全控制结果集的订购方式,那么您的解决方案就是完美的选择。 However, if you have multiple keys, then I would definitely consider using fulltext search because it will be faster and lot less comlicated to code. 但是,如果您有多个键,那么我肯定会考虑使用全文本搜索,因为它会更快并且更不会使代码复杂化。 However, it has a different ranking algorithm than you have now. 但是,它具有与您现在不同的排名算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM