Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "NOT HAVING" syntax like "WHERE XXX NOT IN"?

  1. I have a few queries get the ID numbers of rows that will be deleted in the future.
  2. The row numbers are put into a string and placed in the query below (where you see "2").
  3. I want the results to ignore the rows (as though they have already been deleted).

    SELECT MAX(T1.id) AS MAXid
    FROM transactions AS T1 
    WHERE id NOT IN ( 2 ) 
    GROUP BY T1.position 
    ORDER BY T1.position
    

My guess is that I need to replace the "WHERE" line with "HAVING", but I cannot find "NOT HAVING" syntax.

The way this query is currently written, it will not return a row for T1.position if the max id for the position is listed in the WHERE clause.

How do I get this query to give me the max ID for the T1.position while overlooking the rows with IDs listed in the WHERE clause?

like image 973
Drewneedshelp Avatar asked Mar 09 '11 10:03

Drewneedshelp


People also ask

Can we use not in HAVING clause?

We cannot use the HAVING clause without SELECT statement whereas the WHERE clause can be used with SELECT, UPDATE, DELETE, etc.

What is the correct syntax of HAVING clause?

The following illustrates the syntax of the HAVING clause: SELECT column1, column2, aggregate_function(expr) FROM table GROUP BY column1 HAVING condition; The HAVING clause works like the WHERE clause if it is not used with the GROUP BY clause.

WHERE clause is not used in which command?

WHERE condition; Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE , DELETE , etc.!


2 Answers

HAVING id NOT IN (2) should work; [NOT] IN isn't limited to WHERE clauses.

like image 141
geekosaur Avatar answered Oct 10 '22 20:10

geekosaur


HAVING is not what you need - it is only useful if you want to filter by MAX. For example, if you do not want to get all MAXids but only those larger than 2, you can use HAVING MAXid > 2.

As far as I understand, you want to ignore some rows and calculate the MAXid of the remaining rows. For this purpose, your statement looks correct to me. Afaics a position is not listed in the result set if all its ids are mentioned in your NOT IN clause. This is reasonable since there is nothing left you could calculate a MAX of. If some of a position's ids are listed in NOT IN, while others are not, you should get the MAX of those not listed in NOT IN.

If your result set does not match these expactations, you should debug the string you insert into NOT IN - maybe it accidentally contains too many ids.

like image 41
titanoboa Avatar answered Oct 10 '22 22:10

titanoboa