0

在我的页面中,我使用以下查询来显示从当前时间到旧时间的选择。但它选择从旧时间选择到当前时间选择的行。

我想显示从当前时间到旧时间的选择

$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");

任何人都可以帮我解决这个问题

4

3 回答 3

4

通过子查询包装unioned 查询并在外部查询中对它们进行排序

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
于 2012-12-26T12:57:27.827 回答
3

UNION语法中所述:

要将ORDER BYLIMIT应用于个人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);

但是,使用ORDER BYfor 单个SELECT语句并不意味着行在最终结果中出现的顺序,因为UNION默认情况下会产生一组无序的行。因此,ORDER BY在此上下文中的使用通常与 结合使用LIMIT,因此它用于确定要为 检索的所选行的子集SELECT,即使它不一定影响最终UNION结果中这些行的顺序。如果ORDER BY没有出现LIMIT在 a 中SELECT,它会被优化掉,因为它无论如何都没有效果。

要使用ORDER BYorLIMIT子句对整个UNION结果进行排序或限制,请将各个SELECT语句括起来并将ORDER BYorLIMIT放在最后一个语句之后。以下示例同时使用了这两个子句:

(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;

没有括号的语句等同于刚刚显示的带括号的语句。

于 2012-12-26T12:59:08.093 回答
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
于 2012-12-26T12:59:28.293 回答