如何过滤 mysql 以相同字符开头的选择?

How can I filter mysql selection starting with same characters?

$dir = Volumes/animals/big

我正在 selecting 来自 mySQL table 的值,从特定路径开始:

$sql = "SELECT path FROM files WHERE id = ? AND path LIKE '$dir%'";  
$q = $pdo->prepare($sql);
$q->execute([$id]);
$array = $q->fetchAll(PDO::FETCH_ASSOC);



array(4) {
  [0]=>
  array(1) {
    ["path"]=>
    string(149) "Volumes/animals/big/horses/shetland/amy.jpg" 
  }
  [1]=>
  array(1) {
    ["path"]=>
    string(149) "Volumes/animals/big/horses/shetland/sara.jpg" 
  }
 [2]=>
  array(1) {
    ["path"]=>
    string(149) "Volumes/animals/big/horses/shire/lord.jpg" 
  }
 [3]=>
  array(1) {
    ["path"]=>
    string(149) "Volumes/animals/big/elephant/borneo/mila.jpg" 
  }
[4]=>
  array(1) {
    ["path"]=>
    string(149) "Volumes/animals/big/map.jpg" 
  }

我只需要每个子路径的一个条目。这意味着,这里我有三个以 "Volumes/animals/big/horses" 开头的条目。我只需要一个。我想达到的结果:

 array(2) {
      [0]=>
      array(1) {
        ["path"]=>
        string(149) "Volumes/animals/big/horses/shetland/amy.jpg" 
      }
     [1]=>
      array(1) {
        ["path"]=>
        string(149) "Volumes/animals/big/elephant/borneo/mila.jpg" 
      }
    [2]=>
      array(1) {
        ["path"]=>
        string(149) "Volumes/animals/big/map.jpg" 
      }

我不知道我怎么能做到这一点。我很感激任何想法。

重要提示:我需要直接在 MYSQL select 中使用此过滤器。不在 php

这可以在 MySQL 中完成,因为您将路径的顶层传递到查询中。按如下方式更改您的查询:

$sql = "SELECT path, 
          SUBSTRING_INDEX(SUBSTRING_INDEX(path, '$dir', -1), '/', 2) AS subpath
        FROM files 
        WHERE id = ? AND path LIKE '$dir%'
        GROUP BY subpath";

$dir = 'Volumes/animals/big';时输出:

path                                            subpath     
Volumes/animals/big/elephant/borneo/mila.jpg    /elephant
Volumes/animals/big/horses/shetland/amy.jpg     /horses
Volumes/animals/big/map.jpg                     /map.jpg