具有条件首选项的mysql SELECT

时间:2013-10-12 15:19:41

标签: php mysql database select

我有一个包含4个字段的数据库,我想通过多个或条件从该数据库中搜索用户,问题是如何根据true或条件的数量索引选择。 领域是课程,学校,学院,城市 我希望结果应该根据真实或条件的数量显示这里是代码

    <?php
    $con = mysql_connect("xxx.xx.xxx.xxx","myusername","mypassword");
    if (!$con)
      {
     die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("character", $con);
    $searchfrnd = mysql_query("SELECT * FROM user WHERE (course='physics' or  school='st thomas' or college='mit' or city='austin'))");
    WHILE($display = mysql_fetch_array($searchfrnd))
    {
    $frnd=$display[userid];
    echo $frnd;
    }
    ?>
  • 我只想要显示的结果的优先顺序应该是真OR条件数的递减顺序。换句话说,匹配值的数量的降序顺序

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

select (case when surname = 'jack' then 1 else 0 end +
        case when school ='st' then 1 else 0 end +
        case when college='mit' then 1 else 0 end +
        case when city='austin' then 1 else 0 end) as score,
        *
from 
user 
WHERE surname='jack' or  
      school='st'     or 
      college='mit' or 
      city='austin')
order by score desc;

答案 1 :(得分:1)

尝试此查询:

SELECT *
FROM user 
WHERE surname='jack' 
  OR  school='st' 
  OR college='austin' 
  OR city='mit'
ORDER BY (
  IF(surname='jack', 1, 0)
  + IF(school='st', 1, 0)
  + IF(college='austin' , 1, 0)
  + IF(city='mit', 1, 0)
) DESC;