如何在MySQL查询中设置元素匹配的优先级?

时间:2018-03-13 10:01:09

标签: mysql

我的查询与数据库中的cat, os, device, country匹配。

我希望获得最佳匹配:

  

如果所有cat, os, device, country匹配:等级1

     

如果其中任何三个匹配:等级2

     

如果其中任何两个匹配:等级3

     

如果其中任何一个匹配:等级4

     

如果它们都不匹配:等级5

如何在MySQL中设置上述优先级?

我想要设置优先级的查询如下:

SELECT id, uid, url, rel, title, text, cat, os, device, country, adult, pro, status FROM ads 
WHERE status = 1 
AND type = 0 
AND budget > 0.01 
AND adult = '$adult' 
-- If This Conditions match Rank it 1st
AND (((cat LIKE '%$cat%' AND country LIKE '%$code%' AND os LIKE '%$os%' AND device LIKE '%$device%')
OR   (cat LIKE '%$cat%' AND country = 0 AND os = 0 AND device = 0)
OR   (cat = 0 AND country LIKE '%$code%' AND os = 0 AND device = 0)
OR   (cat = 0 AND country = 0 AND os LIKE '%$os%' AND device = 0)
OR   (cat = 0 AND country = 0 AND os = 0 AND device LIKE '%$device%'))

-- If This Conditions match Rank it 2nd
OR   ((cat LIKE '%$cat%' AND country LIKE '%$code%' AND os = 0 AND device = 0)
OR    (cat LIKE '%$cat%' AND country = 0 AND os LIKE '%$os%' AND device = 0)
OR    (cat LIKE '%$cat%' AND country = 0 AND os = 0 AND device LIKE '%$device%')
OR    (cat = 0 AND country LIKE '%$code%' AND os LIKE '%$os%' AND device = 0)
OR    (cat = 0 AND country LIKE '%$code%' AND os = 0 AND device LIKE '%$device%')
OR    (cat = 0 AND country = 0 AND os LIKE '%$os%' AND device LIKE '%$device%'))

-- If This Conditions match Rank it 3rd
OR   ((cat LIKE '%$cat%' AND country LIKE '%$code%' AND os LIKE '%$os%' AND device = 0)
OR    (cat LIKE '%$cat%' AND country LIKE '%$code%' AND os = 0 AND device LIKE '%$device%')
OR    (cat LIKE '%$cat%' AND country = 0 AND os LIKE '%$os%' AND device LIKE '%$device%')
OR    (cat = 0 AND country LIKE '%$code%' AND os LIKE '%$os%' AND device LIKE '%$device%'))

-- If This Conditions match Rank it 4th
OR   (cat = 0 AND country = 0 AND os = 0 AND device = 0))
ORDER BY RAND() LIMIT 1

1 个答案:

答案 0 :(得分:0)

您需要使用相同的条件来生成如下列:

select id, uid, url, rel, title, text, cat, os, device, country, adult, pro, status, if(cat = 0 AND country = 0 AND os = 0 AND device = 0, 4, if(<conditions for rank 3>, 3, if(<conditions for rank 2>, 2, 1))) as rank FROM ads ...

希望你明白了。