简体   繁体   English

获取组中具有最高ID的值-MySQL

[英]Get value with highest ID in group - MySQL

I'm trying to get the row with the highest ID from a group, rather than the lowest. 我正在尝试从组中获取具有最高ID的行,而不是最低的行。 I heard you have to do that JOIN trick, but it's confusing and I can't get my head around it. 我听说您必须执行JOIN技巧,但这很令人困惑,我无法理解。

My code so far is this: 到目前为止,我的代码是这样的:

$userp0l=//userID
$where=//forumID
    SELECT * 
    FROM `noti` 
    WHERE forum='$where' 
    AND user <>  '$userp0l'
    GROUP BY user 
    ORDER BY `id` 
    DESC

It works, however it is showing the first entry in the group, rather than the latest. 它有效,但是显示的是组中的第一个条目,而不是最新的条目。 Anyone know how I can rewrite this? 有人知道我该如何重写吗?

I just said I'd post all of my code, but looking at it, there's not really much else. 我只是说我会发布所有代码,但是看着它,实际上并没有太多其他东西。 I run this statement: 我运行以下语句:

 $elist = mysql_query("SELECT * FROM `noti` WHERE forum='$where' AND user <>  '$userp0l' GROUP BY user ORDER BY `id` DESC") or die(mysql_error());

It gets the information from the database. 它从数据库获取信息。 The information is grouped so I do not capture a user twice when I go to renter data into the table: 该信息已分组,因此在我将租房者数据放入表中时不会两次捕获用户:

if(mysql_num_rows($elist) > 0){
while($elist_result = mysql_fetch_array($elist)){
  $shownotir=$elist_result['shownoti']; 
  $userr=$elist_result['user'];
  $forumr=$elist_result['forum'];
    if($shownotir=="n"){
            $pps="INSERT INTO `noti`(`user`, `forum`, `shownoti`, `forumn`, `madeby`) VALUES ('$userr', '$where', '0', '$forumn', '$uu')";
        mysql_query($pps) or die(mysql_error());
    }
    else {
        $pps="INSERT INTO `noti`(`user`, `forum`, `shownoti`, `forumn`, `madeby`) VALUES ('$userr', '$where', '1', '$forumn', '$uu')";
        mysql_query($pps) or die(mysql_error());
    }
     }
    }

I need to find if the most recent entry of shownoti is a 1 or a 0 . 我需要确定shownoti最新条目是1还是0 The trouble is, when grouping, it takes the first entry rather than the latest. 麻烦的是,在分组时,它需要第一个条目而不是最新的条目。 So if the most recent entry has a shownoti value of 0 , but the first entry value has a 1 , it will always show 1 as it is seeing the first entry. 因此,如果最新条目的shownoti值为0 ,但第一个条目的值为1 ,则它在看到第一个条目时将始终显示1 I want to order the groups backwards, basically. 我基本上想向后排列组。

Use DISTINCT 使用DISTINCT

SELECT DISTINCT `user`, `shownoti`
FROM `noti` 
WHERE forum = '97' 
AND user <> '9797'
GROUP BY `user`, `shownoti`
ORDER BY `id` DESC

You have to remember that 4 (from 420) is greater than 1 (from 1350) so your sorting may have to be a little different. 您必须记住4(来自420)大于1(来自1350),因此您的排序可能必须有所不同。 I have created an example here . 我在这里创建了一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM