如何在MySQL中使用子字符串进行分组

时间:2017-04-18 07:02:45

标签: php mysql group-by

您好我有一张名为filestatistics的表

id    file    userid    datetime
 1    p1          99    2017-04-15 09:05:10
 2    exp1        99    2017-04-15 09:25:17
 3    p2          99    2017-04-15 09:45:46
 4    exp2        99    2017-04-15 09:55:07

我想根据他们的文件名对每个用户的总条目进行分组,但不包括' ex'字符串。

我的查询是

SELECT file FROM filestatistics WHERE userid = 99 GROUP BY file;

我上面的查询导致4个条目错误。

对每个用户分组文件的正确查询是什么?

所需的输出

2 files for userid = 99 
//since p1 and exp1 are grouped as 1
//since p2 and exp2 are grouped as 1

5 个答案:

答案 0 :(得分:4)

您可以使用REPLACE尝试以下查询:

  function createCustomEvent(type) {
 var event = new CustomEvent("CustomEvent", {"cancelable": true})
    event.initCustomEvent(type, true, true, null);
    event.dataTransfer = {
        data: {
        },
        setData: function(type,val) {
            this.data[type] = val
            this.types[0] = type
        }
        getData: function(type) {
            return this.data[type]
        },
        dropEffect: 'move',
        effectAllowed:'move',
        types: [],
        items: {},
        files:{}

    }

    return event
}
  

演示: http://sqlfiddle.com/#!9/87e4010/7/0

答案 1 :(得分:2)

我还没有对它进行测试,但希望这个可以帮到你: -

SELECT substring_index(file, 'ex', -1) as file_count, count(*)
FROM filestatistics
GROUP BY file_count;

答案 2 :(得分:0)

试试这个:

select replace(file,'ex','') as file,count(userid),userid from filestatistics GROUP BY  userid, replace(file,'ex','')

答案 3 :(得分:0)

我认为这更为一般(例如案例echo '<table class="block" style="border:2px solid #999999; width:175px; background-color: aliceblue; margin-top:-7px"><thead><tr><th style="color:white; background-color:#444444; height:35px;"> <h2>Leaderboard</h2> </th></tr></thead><tbody>'); while ($row = mysqli_fetch_array($query)) { echo "<tr><td style='padding-left:8px;' class='block'><h4><img src='http://www.arcadeicons.com/images/comprofiler/" . $row['playeravatar'] . "' height='35' width='35' style='border-radius:50%'> " . $row['playername'] . "</h4></td></tr>"; } file

= 'exp1ex'

答案 4 :(得分:-1)

substr查询可以用mysql编写。请将此链接视为参考。

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

查询应该像

SELECT文件FROM filestatistics WHERE userid = 99 AND file!= substr(&#34; ex&#34;,0,2)GROUP BY文件;