SELECT * FROM people WHERE user_id='$user_id' ORDER BY time GROUP BY surname [closed]

こ雲淡風輕ζ 提交于 2019-12-10 12:27:53

问题


I need to pull out all the entries in my database that relate to a certain user_id, order them by the time they were entered into the database (this is php unix time() seconds) and then group them by surname so that they sit with entries of the same surname.

This is the query so far.. Although it only gives me a certain amount of entries.

$sql = "SELECT * FROM people WHERE user_token='$user_token'
        ORDER BY time GROUP BY surname";

What is the correct way to use ORDER and GROUP by in order to get all of the results out grouped by the surname but ordered by the time the were entered? Thanks.


回答1:


The ORDER BY clause should be the last, but you have to specify fields to be aggregated.

Such as:

SELECT surname, count(*) 
    FROM people 
    WHERE user_token='$user_token'
    GROUP BY surname
    ORDER BY surname



回答2:


You have an error in your SQL, syntax, SQL-injection vulnerability and probably you are using obsolete database extension. So, here is what it should really look like:

$dsn = "mysql:dbname=$db_name;host=$db_host";
try{
    $pdo = new PDO($dsn, $username, $password);
}
catch(PDOException $e){
    die($e->getMessage());
}
$sql = "SELECT surname, count(id) FROM people WHERE user_token=:usr_token ORDER BY time GROUP BY surname";
$stmt = $pdo->prepare($sql);
if ($stmt->execute(array(':usr_token'=>$user_token))){
    $result = $stmt->fetchAll();
}
else{
    print_r($stmt->errorInfo());
    die("Error executing query");
}

Refer to PDO manual for details



来源:https://stackoverflow.com/questions/7255276/select-from-people-where-user-id-user-id-order-by-time-group-by-surname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!