Am generating sql query string from other stuff. I would like to have an alias and ORDER B for every selected item, mainly so that if two select parts come up with the same alias they will be coerced into unique column names in the result by appending -1, -2 etc rather than having multiple columns with the same name.
Simplified query:
SELECT '6' - `Amt`
FROM tbl
produces a result with column name '6' - `Amt` (as expected).
However, adding an alias:
SELECT '6' - `Amt` AS '6' - `Amt`
FROM tbl
produces an error.
Yet the same format in ORDER BY is fine:
SELECT '6' - `Amt`
FROM tbl
ORDER BY '6' - `Amt`
https://dev.mysql.com/doc/refman/5.7/en/problems-with-alias.html does talk about this.
The only thing I can think to do is strip the alias back to 6 - Amt but that is different to '6' - `Amt` which mysql creates if there is no alias.
Any suggestions?
If you really really really want ` in your alias you can "escape" them by doubling them up, like `6 - ``Amnt```
... but I would recommend against that unless there is a very very good reason for it.
SELECT '6' - 'Amt' as ` '6' - ``Amt`` `
I am unsure with what you are trying to achieve, but this is possible by multiplying the ` in your query.
Im not sure why you would do this since this is bad practise, and I would advice not using this unless you must have to.
Related
INSERT INTO admin(UserID,Username,InitialBid) select ID,username,(select
case
when experience = 'Fundamental' then '1'
when experience = 'Novice' then '2'
when experience = 'Intermediate' then '3'
when experience = 'Advanced' then '4'
when experience = 'Expert' then '5'
end as intbid
from user_details ) from user_details;
In this code I want to add data from one table to another along with a conditional statement column as a sub-query. As it returns multiple rows at a time so it is not able to execute this query.
What should I write that we got value in InitialBid column corresponding to its value?
I really doubt that you want a subquery at all. Doesn't this do what you want?
insert into admin (UserID, Username, InitialBid)
select id, username,
case experience
when 'Fundamental' then 1
when 'Novice' then 2
when 'Intermediate' then 3
when 'Advanced' then 4
when 'Expert' then 5
end as intbid
from user_details;
This inserts one row in the target table for each row in user_details, while transcoding the experience to a literal number.
Notes:
a short-circuit case expression is good enough in this situation (the column is listed only once, at the beginning of the expression)
initialBid looks like a numeric column; if so, remove the single quotes around the literal values that are generated by the case expression, so the database does not need to implicitly cast them.
I've got a table with one column that is a comma separated list of possible values. I'd like to query, grouped by each individual possible value.
As a test, I've written this query:
SELECT
`Please_identify_which_of_the_following_classroom_hardware_you_c2`,
count(`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) as count,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`
GROUP BY
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`,
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
END
(Please excuse the column names, they're auto-generated)
I know the CASE statement isn't incredibly useful at this point, but I'm just trying to get the query to run. I'm getting an error:
ERROR 1064 (42000): 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 'THEN 'Elmo' END' at line 10
For the life of me I can't find what's wrong with the query. Any insight would be appreciated.
EDIT: I've tried with single and double quotes - same problem regardless of the quote used.
UPDATED: As Mark has pointed out, even if I get this query to parse, the results won't be what I'm looking for. I'm still curious why this doesn't parse, but the query is not the solution to my initial problem.
The reason you're seeing issues is that your GROUP BY attributes didn't align with the SELECT attributes.
As the MySql docs put it:
"SQL92 and earlier does not permit queries for which
the select list, HAVING condition, or ORDER BY list refer
to nonaggregated columns that are neither named in the GROUP BY
clause nor are functionally dependent on (uniquely determined by)
GROUP BY columns"
In other words, since the ...c2 attribute was not "functionally dependent on" your CASE ... END attribute, there was a mismatch between SELECT and GROUP BY, and thus an error.
One way to mitigate the error (and possibly make the query more readable), is to do the CASE once and then do the aggregates on the resulting relation.
SELECT c2, tec1, COUNT(tec1)
FROM
(SELECT
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%'
THEN 'Elmo'
ELSE
`Please_identify_which_of_the_following_classroom_hardware_you_c2`
END AS c2,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) AS tec1
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`) t
GROUP BY c2, tec1
Try This:
SELECT
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
ELSE `Please_identify_which_of_the_following_classroom_hardware_you_c2`
END AS `Please_identify_which_of_the_following_classroom_hardware_you_c2`,
count(`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) as count,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`
GROUP BY
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`,
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
ELSE `Please_identify_which_of_the_following_classroom_hardware_you_c2`
END
I'm trying to do this query:
SELECT MAX(`peg_num`)
AS "indicator"
FROM `list`
WHERE `list_id` = 1
AND "indicator" >= 1
But I'm getting the result of NULL. What I should be getting is 99, as the range of peg_num is 00 to 99.
The value checked against "indicator" should actually be a user input, so I want it to be versatile. But, it does give me the correct result if I flip the equality around:
SELECT MAX(`peg_num`)
AS "indicator"
FROM `list`
WHERE `list_id` = 1
AND "indicator" <= 1
Why would it do this?
Edit:
As suggested, I'm using the HAVING clause... but I just ditched the alias for now anyway:
SELECT MAX(`peg_num`) AS "indicator"
FROM `list`
GROUP BY `list_id`
HAVING MAX(`peg_num`) <= 40
Still very stubborn. It gives me 99 now no matter the value in the having clause, regardless of the inequality.
Edit2:
As a clarification:
What I want to happen is the query select the largest value in the range of peg_num, but only if it is larger than a user-given input. So, the max in this case is 99. If the user wants to select a number like 101, he/she can't because it's not in the range.
Because of double quotes, "indicator" in WHERE clause is interpreted as a string. Thus, it evaluates to 0, meaning it is always less than 1. Column names must be escaped in backticks.
Keep in mind that WHERE clause is executed before SELECT an hence aliases defined in SELECT can not be used in WHERE clause.
SELECT MAX(`peg_num`) AS `indicator`
FROM `list`
WHERE `list_id` = 1
HAVING `indicator` >= 1
You might want to check out the link on the answer to another Stack question about not being allowed to use alias in where clause:
Can you use an alias in the WHERE clause in mysql?
Paul Dixon cites:
It is not allowable 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 B.1.5.4, “Problems with Column
Aliases”.
Also:
Standard SQL disallows references to column aliases in a WHERE clause.
The behavior you're seeing in your query when you swap the '<=' and '>=' operators, results from the query comparing the string/varchar 'indicator' to the number 1.
That's why you see the correct answer..when ('indicator' >= 1) which is true, and null when ('indicator' <= 1) which is false.
I don't know, but I'm amazed either of them work at all. WHERE works serially on fields belonging to individual records and I wouldn't expect it to work on "indicator" since that's a group calculation.
Does this do what you want?
SELECT max(`peg_num` ) AS "indicator"
FROM actions
WHERE `peg_num` >=1
AND `list_id` <= 1
WHERE happens before SELECT, and don't know what's "indicator".
You should use HAVING (with GROUP BY) to use the SELECT fields
Here's the documentation for syntax
http://dev.mysql.com/doc/refman/5.5/en/select.html
Something like this is the idea
SELECT MAX(peg_num) AS indicator
FROM list
WHERE list_id = 1
HAVING indicator <= 1
I can't test it and i never met Mysql so just the idea,
You should use HAVING
No quotes in HAVING condition
This must work:
SELECT MAX(peg_num)
AS indicator
FROM list
WHERE list_id = 1
HAVING indicator >= 1
I completely re-invented my query and it worked. The thing is, I had to use a nested query (and I wanted to not do that as much as possible, my professor had always discouraged it).
Anyway, here it is:
SELECT IF(`key` < 900, `key`, null) `key`
FROM (
(
SELECT MAX( `peg_num` ) AS `key`
FROM `list`
WHERE `list_id` =1
) AS `derivedTable`
)
We are selecting a few fields from a database (including a left join) and have managed to order them by a field containing an INT using this command:
ORDER BY FIELD (t.type, '1','2','4','5','3')
That's the order they appear, however we also have entries that contain no integers, they are retuning as NULL. That's fine, but we can't seem to place the NULL entries where we want them.
We want them second in the list, for example:
ORDER BY FIELD (t.type, '1','NULL','2','4','5','3')
or
ORDER BY FIELD (t.type, '1','0','2','4','5','3')
etc...
How can we achieve this and place the entries with a NULL t.type field second in the list?
I've been searching high and low since posting this message but can't find anything on the topic.
Any help is greatly appreciated.
UPDATE:
Here is the full select statement we are using:
select d.url, d.lid, d.title, d.description, d.date, d.hits, d.downloadratingsummary, d.totalvotes, d.totalcomments, d.filesize, d.version, d.homepage, d.ns_compat, d.ns_des_img, t.type from downloads_downloads d LEFT JOIN downloads_type t on d.lid = t.lid where cid=96 ORDER BY FIELD (t.type, 1,12,2,4,5,3), d.date DESC LIMIT 0,20
Is there a value you can substitute for NULL that doesn't appear anywhere else? Something like:
ORDER BY FIELD(coalesce(t.type, -1), '1', '-1', '2', '4', '5', '3')
By the way, the arguments can also be numbers instead of strings:
ORDER BY FIELD(coalesce(t.type, -1), 1, -1, 2, 4, 5, 3)
Remove the quotes around NULL. It's not a string. In fact, remove the quotes around the numbers as well. They probably don't hurt in that case, but they're also not strings.
If that doesn't work, I'm not sure how to properly handle it. The MySQL doc for FIELD() says:
If str is NULL, the return value is 0 because NULL fails equality comparison with any value.
So, as you tried in your third example, you might have to use 0, but perhaps removing the quotes will fix it.
why not do this in your SELECT statement something like
SELECT IFNULL(t.type, 2)
FROM table_name t
Here you are assigning the value of 2 to any NULL values. Does this work for you?
try this
ORDER BY CASE `t.type`
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '4' THEN 3
WHEN '5' THEN 4
WHEN '3' THEN 5
WHEN null THEN 6
END
Trying to select a query in php/mysql to get "Upcoming Items" in a calendar. We store the dates in the DB as a unix time. Here's what my query looks like right now
SELECT *
FROM `calendar`
WHERE (`eventDate` > '$yesterday')
OR (FROM_UNIXTIME(eventDate, '%m') > '$current_month' AND `$yearly` = '1')
ORDER BY `eventDate`
LIMIT 4
This is giving me an error "Unknown column '' in 'where clause'". I'm sure it has to do with my use of parenthesis (which I've never used before in a query) and the FROM_UNIXTIME command.
Can someone help me out and let me know how I've screwed this up?
Thanks!
This to me looks suspicious:
`$yearly`
What is the value of $yearly? Is it empty? When you use backticks MySQL treats the contents as the name of a column.
Perhaps you meant to create a string instead, in which case you should use a different type of quote:
'$yearly' = '1'
Or perhaps you intended to refer to the column yearly:
yearly = '1'
Another tip is to print the SQL query after the PHP variables have been interpolated as this sometimes makes it easier to understand the error message from MySQL. I'd imagine your query looks something like this:
SELECT *
FROM `calendar`
WHERE (`eventDate` > '1295071200')
OR (FROM_UNIXTIME(eventDate, '%m') > '1' AND `` = '1')
ORDER BY `eventDate`
LIMIT 4
The suspicious part is here:
`` = '1'
Do you have a column named $yearly ?, try removing the dollar sign