SQL MAX in conjunction with WHERE clause - php

I need to find the largest value from one particular column in a mysql table where the value of another column is equivalent to something. But, with the query that I'm using, I keep on getting a message that displays and SQL error. My query is aS follows:
SELECT MAX(message_id) AS top_message HAVING(child_id) = '".$message_id[$i]."'
Any suggestions?

You are also missing a table name:
SELECT MAX(message_id) AS top_message FROM tablename WHERE child_id = '".$message_id[$i]."'

You should use WHERE instead of HAVING Clause:
SELECT MAX(message_id) AS top_message
FROM tablename
WHERE child_id = '".$message_id[$i]."'
Use only HAVING clause when you have an aggregated conditon.

You need a from clause and a where clause. The having clause is used for group filters. You don't have a group by clause, so there is no reason to write a having clause. If the table where you want to select from is called 'MyTable', then your query is as follows:
SELECT MAX(message_id) AS top_message
FROM MyTable
WHERE child_id = '".$message_id[$i]."'
Note, that the paranthesis around child_id is not needed. Please read SQL and MySQL tutorials for more information, your life will be much easier.

Related

update with max value of the column is not working in mysql

I have tried to set the max value for the particular column but that is not working for me. I do not know where i'm going wrong.
UPDATE `upload_video`
SET order_id ='select max(order_id)+1
FROM upload_video'
WHERE `video_id` = 22
This is my query i run the select max(order_id)+1 from upload_video query separately which is giving the result. But if i use this query in update query, the query is executing without error. But the order_id is not updating properly. please help me
Your query is almost correct in standard SQL, you only need to use brackets () instead of apostrophe ':
SET order_id = (SELECT MAX(...) ...)
but MySQL doesn't allow you to update a table while selecting from the same table, a workaround is to use a subquery that calculates the value that you need, and to join your subquery with the table you need to update:
UPDATE
upload_video JOIN (SELECT COALESCE(MAX(order_id),0)+1 max_id
FROM upload_video) s
SET
upload_video.order_id=s.max_id
WHERE
video_id=22
Please see fiddle here.
You have a typo in the statement, you used UPADTE instead of UPDATE.
One problem is, don't quote the subquery. You have used single quotes, which means the expression select max(order_id)+1... was interpreted as a text literal (a varchar). But you clearly don't want that (I guess order_id is a number). What you want instead is to evaluate the subquery. However, if you try:
UPDATE `upload_video`
SET order_id =(select max(order_id)+1
FROM upload_video)
WHERE `video_id` = 22
then MySQL doesn't allow it (I didn't know about that). Other databases such as PostgreSQL allow it. So you might need two statements:
select #id = coalesce(max(order_id), 0) + 1 FROM upload_video;
UPDATE `upload_video` SET order_id = #id WHERE `video_id` = 22;
Please note this works in MySQL but not in other databases.
Try this:
UPDATE `upload_video`
SET order_id =(select COALESCE(max(U2.order_id),0)+1
FROM upload_video U2)
WHERE `video_id` = 22
Peraphs this query goes in error because MySql doesn't want to use the same table in UPDATE and in subquery.
If your case please write two queries.
The first get the maximum value, the second does update

sql count() and *

Is this possible in sql :
COUNT(ads.id) AS ads, *
If not, then what to use? I'm using LEFT JOIN, there are two tables: ads and ad, but I'm not using GROUP BY:
SELECT COUNT(ads.id) AS ads_count,
ads.*
FROM ...
It's not working.
It's certainly possible to include a * in the SELECT list alongside other columns, in general. But COUNT() is an aggregate function, and the implication there is that you're grouping by every other column in the resultset, which is probably not true.
Whether or not that query will function may be heavily dependent on which DBMS you're using, which you haven't specified. In MS SQL Server, you must declare all non-aggregate columns in a GROUP BY clause, and * is not a valid member in a GROUP BY clause, hence in SQL Server that's an invalid query.
MySQL seems to have somewhat looser rules around grouping and using aggregate functions, so it's possible that query may be syntactically valid (I don't have a MySQL database handy to test it), but its results would almost certainly be indeterminate...
You could do something like this:
-- test table
declare #T table(name varchar(10), number int)
select *, count(name)
from #T
group by number, name
In MSSQL, if you select * then you would have to list all of the columns in the group by.
Of course the only counts that would be greater then 1 would be for duplicated rows.
This should work:
SELECT COUNT(ads.id) AS ads_count,
ads2.*
FROM table_name ads
JOIN table_name ads2
GROUP BY ads.id
table_name should be your table name.

SQL SELECT Question

I am trying to perform a SQL query that acts in two parts.
First, I have a query that returns a list of 10 Ids.
But then I want to have a SELECT statement which has a WHERE clause for each of these 10 ids.
Is this possible?
I tried:
SELECT * FROM tablenameWHERE id= (SELECT id FROM table_of_ids WHERE
tableid='1a177de1-3f25c9b7910b' OR
tableid='64faecca-133af807a65a' OR
... up to 10 Ids)
but it returns with an error stating the subquery returns more than 1 row.
Note, the tableid and id columns of table_of_ids are different values.
Does anyone know how to accomplish this?
I seem to be at a loss myself.
If it matters, I am using mySQL and PHP.
Cheers,
Brett
Not a very optimized query, but you could use IN instead of =
SELECT * FROM tablename WHERE id IN (SELECT id FROM table_of_ids WHERE
tableid='1a177de1-3f25c9b7910b' OR
tableid='64faecca-133af807a65a' OR
... up to 10 Ids)
Change it to in()
WHERE id IN (SELECT id ...)
Replace the = with the IN keyword.
select * from sometable where key in (subselect that returns one column)
Looks like you can;
SELECT *
FROM tablename
INNER JOIN table_of_ids ON table_of_ids.id = tablename.id
WHERE table_of_ids.tableid IN (
'1a177de1-3f25c9b7910b',
'64faecca-133af807a65a',
... )
Don't use the "=" operator, use the "IN" operator.
See this tutorial for examples.
Use IN keyword.
SELECT * FROM user WHERE Id IN(SELECT userId FROM table).
Id is primary key of your first table and userId is foreign key in second table of coz.

Mysql Where Alias equals

given a table 'my_table' with columns col1,col2.
Is it possible to write a query like this
SELECT col1 as my_alias,col2 FROM my_table WHERE my_alias = 'value'
I have tried it but get an unknown column 'my_alias' in where clause.
For the curious, the reason I am doing this is:
I have a table with a composite primary key. When I retrieve information from that table I concatenate the cols that make up the primary key into an Id which can then be used in my url's to identify particular records. Then when I want to return only the given record I select the record where it is = my alias. Not sure if this is a good idea, feel free to comment.
Note: The standard way to do this query is:
SELECT col1 as my_alias,col2 FROM my_table WHERE col1 = 'value';
No, it is not allowed. From the MySQL manual:
12.2.8. SELECT Syntax
...
It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section C.5.5.4, “Problems with Column Aliases”.
And:
C.5.5.4. Problems with Column Aliases
An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column.
...
Standard SQL disallows references to column aliases in a WHERE clause.
To fix it you should write your query as follows:
SELECT col1 AS my_alias, col2
FROM my_table
WHERE col1 = 'value'
If col1 is not actually a single column but a more complicated expression then you should be aware that using it in your WHERE clause will most likely prevent efficient usage of an index and result in a full scan. This could hurt the performance of your application if the table grows large.
It's not directly possible but you could use a subselect and use the column alias in the outer select:
select my_alias, col2
from (SELECT col1 as my_alias,col2 FROM my_table) as x
WHERE my_alias = 'value'
You can use it in HAVING clause.

PHP/Mysql Columns imageid, catid, imagedate, userid

I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX

Categories