Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL max selecting max value but pairing with incorrect row
    primarykey
    data
    text
    <p>I'll start off by showing you what my database looks like with some example data:</p> <pre><code>| id | type | id_user | date | | 0 | 0 | 1 | 1 | | 1 | 0 | 2 | 2 | | 2 | 1 | 1 | 3 | | 3 | 0 | 3 | 4 | | 4 | 0 | 1 | 5 | | 5 | 1 | 1 | 6 | </code></pre> <p>What this is tracking is when people leave or join groups and I'm trying to get how many people are in a group.</p> <p>For example this tables history would look like: (type 0 = joins, type 1 = leaves)</p> <pre><code>user 1 joins at time 1 user 2 joins at time 2 user 1 leaves at time 3 user 3 joins at time 4 user 1 joins at time 5 user 1 leaves at time 6 </code></pre> <p>So if I where to query how many people are in the group it would be 2 because user 1 left 2 times and there are only user 2,3 in the group now.</p> <p>I've been playing around for the past hour and a half but cant seem to get anything to work. I'm really confused with MAX() because its not returning what I would think is the correct result (though I'm aware I'm doing something completely wrong)</p> <pre><code>SELECT *,MAX(date) from myTable GROUP BY id_user </code></pre> <p>The above is my current thinking but its not giving me anything that I want. </p> <p>I went into PHPMyAdmin and tried very simple MAX() just to get the largest date (I know you can do that by ORDER BY date DESC but that's not what I'm looking for. This is just a test):</p> <pre><code>SELECT *,MAX(date) from myTable </code></pre> <p>This, however, would return the first row in the list. So I played around a little more and put in a MAX(date) as D and what I found was it was really returning the first column and then slapping on the highest date:</p> <pre><code>| id | type | id_user | date | D | | 0 | 0 | 1 | 1 | 6 | </code></pre> <p>I've tried googling this and looked through other SO questions but can't find anything that fixes my problem. If anyone has any idea what I'm doing wrong with MAX or has any suggestions on approaches to this I'd be really grateful. (I have a feeling my query will have to be much more intensive.) Anyways, thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload