MySQL过滤器包含两行以上的字符串计数

时间:2015-08-13 09:53:37

标签: php mysql

我有下表(tbl_name)

username | app
--------------
user1      app1
user1      app2
user2      not an app
user3      not an app
user3      app3
user3      app1
user4      app1

我想计算使用多个应用的​​用户。

我设法只获得使用应用程序查询的用户

SELECT DISTINCT username, app
FROM tbl_name
WHERE app LIKE \"%@%\"
OR app LIKE \"%Desktop%\"
OR publishedapp LIKE \"%RDP%\"
ORDER BY username

(使用WHERE和LIKE来获取我想列出的案例)

这会返回类似这样的内容

username | app
--------------
user1      app1
user1      app2
user3      app3
user3      app1
user4      app1

现在,我试图获得使用多个应用的​​用户,如果有以上情况,将会返回:

user
-----
user1
user3

使用多个应用的​​用户:2

我尝试过使用计数器,但还没有找到正确实施的方法。

以下是代码,我也不知道我是否通过结果正确迭代

<?php

$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT DISTINCT username, publishedapp
FROM tbl_name
WHERE publishedapp LIKE \"%@%\"
OR publishedapp LIKE \"%Desktop%\"
OR publishedapp LIKE \"%RDP%\"
ORDER BY username";

$result = $conn->query($sql);

for ($i=0; $i < $result->num_rows; $i++) {
  $row = $result->fetch_assoc();

  echo $i .".- ". $name1 = $row["username"] ." (". $app1 = $row["publishedapp"] ." )";

  echo "<br><br>";
}
$conn->close();
?>

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试使用group by子句和group_concat

SELECT username, group_concat(app), count(app)
FROM tbl_name
WHERE app LIKE \"%@%\"
OR app LIKE \"%Desktop%\"
OR publishedapp LIKE \"%RDP%\"
group by username
ORDER BY username 

如果您需要有app > 1的条件用户,那么只需在having之后使用group by作为

having count(app) > 1

答案 1 :(得分:1)

试试这个

SELECT username, app, COUNT(app)
FROM tbl_name
WHERE GROUP BY username HAVING COUNT(app) >= 1