当人们在我的网站上搜索时,我使用UNION查询从不同的表中引入结果。人员,地点和活动。
我想按字母顺序对“人物”,“场地”按字母排序,对事件“ 反向”按字母排序,因为它们以一年开始,所以我希望最近的事件排在最前。 >
这是我目前所拥有的(已大大简化,但您明白了)。除了我希望对事件进行反向排序之外,它运行得很好。
我可以通过这个UNION查询达到最终目的,还是需要将其分解为多个单独的查询?如果需要的话,我没有问题,但是由于代码可以正常工作,因此,如果有人可以想到一个巧妙的技巧,我希望对下面的查询做一个小的简单更改。
SELECT name AS name
, name AS order
, 1 AS grp
FROM PEOPLE
UNION
SELECT venue AS name
, venue AS order
, 2 AS grp
FROM VENUES
UNION
SELECT event AS name
, event AS order
, 3 AS grp
FROM EVENTS
ORDER BY grp ASC, order ASC
例如,如果我可以将event AS order
更改为STRING_SUBTRACT('ZZZZZZ', event) AS order
或类似的名称。我可以使用任何此类功能吗?
答案 0 :(得分:1)
UNION只会在一个表之后追加另一个表。编写三个简单的查询,并在它们之间使用联合。在您的情况下,按条件应用三种不同的顺序,就像您在前面的示例中一样,对每个查询应用一种。
(SELECT name AS name
, name AS order
, 1 AS grp
FROM PEOPLE
ORDER BY name asc)
UNION
(SELECT venue AS name
, venue AS order
, 2 AS grp
FROM VENUES
ORDER BY venue ASC)
UNION
(SELECT event AS name
, event AS order
, 3 AS grp
FROM EVENTS
ORDER BY event DESC)
不同的故事,如果要订购统一的结果,将它们混合在表之间
答案 1 :(得分:1)
这是我到目前为止提出的答案:
SELECT name AS name
, name AS orderByAsc
, '' AS orderByDesc
, 1 AS grp
FROM PEOPLE
UNION
SELECT venue AS name
, venue AS orderByAsc
, '' AS orderByDesc
, 2 AS grp
FROM VENUES
UNION
SELECT event AS name
, '' AS orderByAsc
, event AS orderByDesc
, 3 AS grp
FROM EVENTS
ORDER BY grp ASC
, orderByDesc DESC
, orderByAsc ASC
完美运行。