我想知道,我们如何在基于Union的mysql_query中订购列表(DESC),当我们在PHP / MYSQL中获取此查询时,我们正在获取输出。但我们只是简单地将订单放在此查询中。
(SELECT info.id
FROM info, 1_all
WHERE 1_all.id = info.id and 1_all.table_type = 'disp' AND 1_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY resinfo.id )
UNION ALL
(SELECT info.id
FROM info, 2_all
WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY info.id)
答案 0 :(得分:4)
使用ORDER BY或LIMIT子句对整个UNION进行排序或限制 结果,括起单个SELECT语句并放置 最后一个之后的ORDER BY或LIMIT。以下示例使用两者 子句:
(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;
答案 1 :(得分:0)
您可以制作这样的子查询:
SELECT info.id
FROM
(
(SELECT info.id
FROM info, 1_all
WHERE 1_all.id = info.id and 1_all.table_type = 'disp' AND 1_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY resinfo.id )
UNION ALL
(SELECT info.id
FROM info, 2_all
WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY info.id)
) as all
order by id desc;
答案 2 :(得分:0)
我不知道MySQL引擎是否接受它,但SQL Server等其他引擎允许你在最后添加order by子句:
SELECT info.id
FROM info, 1_all
WHERE 1_all.id = info.id and 1_all.table_type = 'disp' AND 1_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY resinfo.id
UNION ALL
SELECT info.id
FROM info, 2_all
WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6)
GROUP BY info.id
ORDER BY info.id DESC;
如果您的数据库引擎不接受它,那么您最好的选择是根据您的联合查询创建一个视图,然后根据您的订单查询此视图。