在我的页面中,我使用以下查询来显示从当前时间到选择的旧时间的选择。但它选择从旧时选择到当前时间选择的行。
我想显示从当前时间到旧时的选择
$result=mysql_query("(SELECT choice_id,poll_id,choicecreationtime from je_addchoice ORDER BY choicecreationtime DESC)
UNION
(SELECT choice_id,poll_id,datetime_voted from je_user_vote ORDER BY datetime_voted DESC)");
我不知道为什么会出现这个问题。如果我不使用UNION意味着它工作正常。例如。以下查询显示当前时间到旧
的顺序 $result = mysql_query("SELECT * FROM je_addchoice, je_addpoll where je_addpoll.privacy='0' AND je_addpoll.start_date <= '$check_date' AND je_addpoll.end_date >='$check_date' AND je_addpoll.poll_id=je_addchoice.poll_id order by je_addchoice.choicecreationtime desc");
任何人都可以帮我解决这个问题
答案 0 :(得分:4)
通过子查询包装union
ed查询,并在外部查询
SELECT *
FROM
(
SELECT choice_id, poll_id, choicecreationtime AS TIME
FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted AS TIME
FROM je_user_vote
) s
ORDER BY TIME DESC
更新1
SELECT choice_id, poll_id, choicecreationtime AS TIME
FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted AS TIME
FROM je_user_vote
ORDER BY Time DESC
答案 1 :(得分:3)
正如UNION
Syntax所述:
要将
ORDER BY
或LIMIT
应用于个人SELECT
,请将该子句放在括起SELECT
的括号内:(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
但是,对于单个
SELECT
语句使用ORDER BY
并不意味着行在最终结果中出现的顺序,因为默认情况下UNION
会生成一组无序行。因此,在此上下文中使用ORDER BY
通常与LIMIT
结合使用,因此它用于确定要为SELECT
检索的所选行的子集,即使它不一定会影响最终UNION
结果中这些行的顺序。如果ORDER BY
中LIMIT
出现ORDER BY
,则会对其进行优化,因为它无论如何都无效。要使用
LIMIT
或ORDER BY
子句对整个SELECT
结果进行排序或限制,请为各个UNION
语句添加括号并放置LIMIT
或{ {1}}在最后一个之后。以下示例使用两个子句:(SELECT a FROM t1 WHERE a=10 AND B=1) UNION (SELECT a FROM t2 WHERE a=11 AND B=2) ORDER BY a LIMIT 10;
没有括号的语句相当于刚刚显示的一个括号。
答案 2 :(得分:1)
试试这个:
SELECT choice_id, poll_id, dt
FROM (SELECT choice_id, poll_id, choicecreationtime dt FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted dt FROM je_user_vote ) AS A
ORDER BY dt DESC