【问题标题】:Fetch a particular list from table and fetch the remaining afterwards, using MySQL使用 MySQL 从表中获取特定列表,然后获取剩余的列表
【发布时间】:2013-11-06 02:48:35
【问题描述】:

这是我曾经想过的复杂查询。我知道这将是一个更愚蠢的问题。

我有一个 id 数组,其中包含 100 多个 id。我想从数据库中获取所有内容,但首先是等于 id 的列表,然后我想要剩余的。

我的尝试:

PHP:

$arr = array(3,1,4);
sort($arr)
$implodedArr = implode(" || id = ", $arr);

Mysql:

SELECT * FROM tablename WHERE id = implodedArr;

我认为我所做的一切都不对。

【问题讨论】:

    标签: php mysql arrays sorting fetch


    【解决方案1】:

    试试这个。首先的策略是使用IN 运算符,而不是使用大量串联的OR 语句——这应该更快。然后我们可以使用UNION 来合并第一组中没有出现的那些。

    我已将搜索结果标记为具有“important=1”的虚拟列,用于排序目的,但您可以根据需要将其更改为更有意义的内容。

    PHP:

    $arr = array(3,1,4);
    sort($arr)
    $implodedArr = implode(",", $arr);
    

    MySQL:

    SELECT
        *, 1 AS important FROM tablename WHERE id IN ($implodedArray)
    UNION
    SELECT
        *, 0 AS important FROM tablename WHERE id NOT IN ($implodedArray)
    ORDER BY
        /* You can order by other fields after "important" if you wish */
        important DESC;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-29
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2021-10-16
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多