I am having trouble with doing a SUB SELECT in an IF() condition.
I'm trying to get it to select select the MIN saved time if the type does not equal a certain value, excluding that value from the calculation.
Here is my current SQL query that works except for the IF():
SELECT
t.episode,
t.anime_id,
MAX(t.type) as type,
MIN(t.HD) as HD,
MAX(t.thumbnail) as thumbnail,
IF((MAX(t.type)!="raw"),(SELECT MIN(e.saved) FROM anime_episodes e WHERE e.type=MAX(t.type) AND t.episode=e.episode AND t.anime_id=e.anime_id GROUP BY e.anime_id, e.episode), (MIN(t.saved))) as time,
// UP HERE ^
MAX(t.filler) as filler,
m.anime_name,
m.furl,
m.video_thumb
FROM anime_episodes t
LEFT JOIN anime_list m ON
( t.anime_id=m.anime_id )
WHERE t.approved=1 AND t.locked=0 AND m.status=0 AND t.episode>=m.latest_ep
GROUP BY t.anime_id, t.episode
ORDER BY time DESC LIMIT 0,24
Is there something going on with my syntax? It looks fine to me but the error is:
SQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE type!="raw")) as time, MAX(t.filler) as filler,m.anime_name, m.furl, m.vid' at line 1
EDIT: Correct answer, but I had to add some grouping as it was returning more than one result. Thank you!
You have forgot to add the from table statement
Try this::
SELECT
t.episode,
t.anime_id,
MAX(t.type) as type,
MIN(t.HD) as HD,
MAX(t.thumbnail) as thumbnail,
IF((type="raw"),(MIN(t.saved)), (SELECT MIN(saved) from anime_episodes WHERE type!="raw")) as time,
// UP HERE ^
MAX(t.filler) as filler,
m.anime_name,
m.furl,
m.video_thumb
FROM anime_episodes t
LEFT JOIN anime_list m ON
( t.anime_id=m.anime_id )
WHERE t.approved=1 AND t.locked=0 AND m.status=0 AND t.episode>=m.latest_ep
GROUP BY t.anime_id, t.episode
ORDER BY time DESC LIMIT 0,24
Related
Can anyone help me answer why my query returns a syntax error? I'm working on the Hackerrank problem linked here.
Here's the code I wrote:
SELECT MAX(SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings
I get the following syntax error:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near 'SELECT e1.salary * e1.months FROM Employee
as e1) as max_tot_earnings, COUNT(e.e' at line 1
I know that the subquery doesn't have a syntax error. It runs just fine when run on its own. I was also able to work around the problem, so the purpose of this question is to try and figure out what's going on. I was able to solve the problem with the query shown below:
SELECT (SELECT e1.salary * e1.months as tot_earnings FROM Employee as e1 ORDER BY tot_earnings DESC LIMIT 1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
GROUP BY e.salary, e.months
HAVING e.salary * e.months = max_tot_earnings
I found a few questions here that touch on using SELECT MAX(SELECT ...), but I didn't find answers for the two questions as phrased above. Questions one, two, and three.
In sum, I have two main questions:
Why does the SELECT MAX(SELECT ...) approach return a syntax error? I've used MAX(SELECT ...) statements in HAVING before, so I'm puzzled. Are aggregate functions with subqueries just not allowed in SELECT?
In my search online for an answer to #1, I have seen suggestions move the subquery in the FROM statement. Is this preferable to having the subquery in my SELECT statement (as in my eventual solution shown above)?
The correct syntax is:
SELECT (SELECT MAX(e1.salary * e1.months) FROM Employee as e1) as max_tot_earnings,
COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings;
Or more simply as:
SELECT (e.salary * e.months) as max_tot_earnings, COUNT(*)
FROM Employee
GROUP BY max_tot_earnings
ORDER BY max_tot_earnings DESC
LIMIT 1;
Your query doesn't work for the following reasons:
A subquery needs its own set of parentheses. So does a function call. So MAX( (SELECT . . . ) ) at least meets the parentheses requirements.
The MAX() function takes an argument that is either a column reference or a constant or an expression that evaluates to a scalar. Your function call does not do that.
MAX() doesn't allow subqueries at all, even scalar subqueries.
This it the code I am trying to execute:
SELECT ID_K
FROM koncert,
programi
WHERE koncert.ID_K = programi.ID_K
GROUP BY koncert.ID_K
HAVING COUNT (DISTINCT programi.Salla) = 2
It returns this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to
your MariaDB server version for the right syntax to use
near 'DISTINCT programi.Salla)=2 LIMIT 0, 25' at line 4.
Tried to change different things but it still won't work .
You should use the count(DISTINCT programi.Salla
) and not count (..) ..remove space between COUNT and (...
SELECT koncert.ID_K
FROM koncert
INNER JOIN programi on koncert.ID_K = programi.ID_K
GROUP BY koncert.ID_K
HAVING COUNT(DISTINCT programi.Salla) = 2
but you need also tablename for avoid ambiguity and use explicit join sintax too
First you should use qualified name for your column, when column name is same in both table
SELECT ID_K FROM
should be
SELECT programi.ID_K FROM
else, you will get ambiguous column error. Otherwise, your query looks fine except removing extra space when calling COUNT (#spencer already mentioned in comment)
Also, it is good practice to join your table using JOIN (or INNER JOIN, LEFT JOIN etc) keyword, which makes your query more clear and readable.
I want to fetch entire record with distinct field points so I wrote following query but it is not giving desired result.
#top_score_cards = Score.select("DISTINCT points *").order("points DESC , updated_at DESC").where("points != ? And activity_id= ? ",0,params[:#myActivity]).limit(3)
It is throwing following error :
Mysql2::Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server versi on for the right syntax to
use near 'FROM scores WHERE (points != 0 And activity_id= '1' )
ORDER BY points DE SC ,' at line 1: SELECT DISTINCT points * FROM
scores WHERE (points != 0 And activity_id= '1' ) ORDER BY poi nts
DESC , updated_at DESC LIMIT 3
The logic of what you're asking for doesn't really make sense, since select will just return the points but you want the whole record.
I think i can guess what it's supposed to be though since i answered another related question earlier. :)
Am i right in thinking that you want one record for the 3 highest unique "points" value in the table, and when there is more than one record with the same points you want the one with the earliest updated_at? if so, then the key to this is group by, not select.
#top_score_cards = Score.group(:points).order("points DESC , updated_at").where("points <> ? and activity_id = ? ",0,params[:activity_id]).limit(3)
I've taken the liberty of fixing lots of syntax errors in your code, so i can't guarantee this this will work or is even what you want.
Then try this instead:
Score.where("points != ? And activity_id= ?",0,params[:#myActivity])
.order("points DESC, updated_at DESC")
.limit(3)
.uniq! { |x| x.points }
Based on the documentation: http://apidock.com/rails/ActiveRecord/QueryMethods/distinct
Trying to run this query:
SELECT FROM_UNIXTIME(offers_consumers_history.date,
`'%d-%m-%Y')` AS date,
COUNT(*) AS COUNT
FROM (`offers_history`)
JOIN `offers_consumers_history` ON `offers_consumers_history`.`offer_history_id`=`offers_history`.`id`
WHERE `offers_history`.`merchant_id` = 1
AND `offers_history`.`offer_type_id` = 1
GROUP BY DATE(FROM_UNIXTIME(offers_consumers_history.date))
ORDER BY `offers_consumers_history`.`date`
If I run it without a date format on my first FROM_UNIXTIME (the %d-%m-%Y part), everything runs fine, but I'm obviously not getting the right date format displayed, the returned error is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (`offers_history`) JOIN `offers_consumers_history` ON `offers_consumers_his' at line 2
Without a date format I'm getting results such as:
{"date":"2010-08-18 18:40:00","count":"2"}
What I want is:
{"date":"18-08-2010","count":"2"}
count is a reserved word, you can't use it as alias, use different name
'%d-%m-%Y') AS dt,
COUNT(*) AS cnt
OR with backticks
(offers_consumers_history.date,'%d-%m-%Y') AS `date`,
COUNT(*) AS `COUNT`
Remove the () from the table name and change the alias name of count:
SELECT FROM_UNIXTIME(offers_consumers_history.date,
'%d-%m-%Y') AS `date`,
COUNT(*) AS cnt
FROM `offers_history`
JOIN `offers_consumers_history` ON `offers_consumers_history`.`offer_history_id`=`offers_history`.`id`
WHERE `offers_history`.`merchant_id` = 1
AND `offers_history`.`offer_type_id` = 1
GROUP BY DATE(FROM_UNIXTIME(offers_consumers_history.date))
ORDER BY `offers_consumers_history`.`date`
i have a query that fetches data's from differant tables
SELECT p.USER_NAME,count(*) as total, pi.UpdatedDate FROM purchase p JOIN purchasedissues pi on pi.PurchaseId=p.PURCHASE_ID WHERE pi.UpdatedDate>DATE_SUB(NOW(), INTERVAL 1 HOUR) AND p.PURCHASE_DATE=CURDATE() AND p.USER_NAME NOT IN (SELECT username from tbl_test_user) GROUP BY p.USER_NAME having count(*)>2
but i got an error that
#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'SELECT p.USER_NAME,count(*) as total, pi.UpdatedDate FROM
purchase p JOIN pur' at line 1
i can't figure it. please any one help me
thanks in advance
Your query is ok. The error is indicating that it is near your SELECT p.USER_NAME,.... This usually happens when you are executing multiple query without terminating it. Ex,
SELECT * FROM tableName
SELECT p.USER_NAME,count(*) as total, pi.UpdatedDate FROM purchase....
so to correct it, just add a delimiter (usually if not change, it's semi-colon) to end your first query
SELECT * FROM tableName; -- <== this one
SELECT p.USER_NAME,count(*) as total, pi.UpdatedDate FROM purchase....
Try this query! not sure if it works as I don't have the environment set in my machine but it may give you an essence to test it :)
SELECT p.USER_NAME,count(*) as total FROM purchase p JOIN purchasedissues pi on pi.PurchaseId=p.PURCHASE_ID WHERE pi.UpdatedDate>DATE_SUB(NOW(), INTERVAL 1 HOUR) AND p.PURCHASE_DATE=CURDATE() AND p.USER_NAME NOT IN (SELECT username from tbl_test_user) GROUP BY p.USER_NAME having total > 2