开发者

mysql: Unknown Column Error in Query

I was writing this query into a shell script so all the double quotes are escaped and there timestamps are variables.

This query works if i don't use the "order by" on terminal.

also there is a strange thing that if the execute the query part in the PHPMYADMIN then then "order by" works. but if i run this query in terminal it gives me UNKNOWN COLUMN QID error

SELECT 'GUIDE-NAME','QUESTION-ID','A开发者_运维技巧CTION','TIMESTAMPS' 
UNION 
SELECT 
SUBSTRING(B.msg,LOCATE('q_id',B.msg)+5, (LOCATE('\"',B.msg)+2) ) AS qid, B.ts 
FROM TABLE B, TABLE A 
WHERE 
       LOCATE('q_id',B.msg) > 0 
       AND A.g_id=B.g_id and B.ts > from_unixtime($DateWeekBefore) 
       AND B.action 
       IN(\"review_question\",\"send_back",\"send_review\",\"publish\",\"quiet_publish\")  
ORDER BY qid 
INTO OUTFILE '/tmp/$vr9$DateWeek.csv' 
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '\"' 
LINES TERMINATED BY '\n'


MySQL tries to apply order by on all query, not on a sub-select. In order to separate sub-selects use brackets:

(select ....) union (select.... order by something)

It seems that INTO OUTFILE can't be used directly in unions, so we need to make a union as a subquery:

SELECT * FROM ( 
    (
        SELECT 'GUIDE-NAME','QUESTION-ID','ACTION','TIMESTAMPS'
    ) UNION (
        SELECT.... ORDER BY qid
    ) 
) a 
INTO OUTFILE ....


As Karolis noted, that ORDER BY is only being applied to the second query in your UNION.

Try this:

SELECT *
FROM
(
 [your whole query]
) AS some_subquery
ORDER BY qid
INTO OUTFILE ...


qid is an alias. Instead of

ORDER BY qid

Try this:

 ORDER BY SUBSTRING(B.msg,LOCATE('q_id',B.msg)+5, (LOCATE('\"',B.msg)+2) )

Edit: My guess is PHPADMIN is smart enough to see that it's an alias and translates it, whereas the terminal does not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜