在mysql中使用UNION时无法排序

时间:2015-03-12 10:28:51

标签: php mysql sql union sql-order-by

如果我不做UNION,我有这个查询正常工作:

SELECT t1.offer_id, t1.cpv_id, t1.type,
FROM `offer_cpv` t1
JOIN `offer` t2     ON t1.offer_id = t2.id
JOIN `company` t3   ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid
AND t3.status IN (4, 6)
GROUP BY t1.offer_id
ORDER BY t1.type

关键部分是我正在做ORDER BY t1.type。但是,如果我使用UNION(我必须),我的查询会断言:

  

'order clause'中的未知列't1.type'

以下是我的UNION尝试不起作用:

SELECT t1.offer_id, t1.cpv_id, t1.type,
FROM `offer_cpv` t1
JOIN `offer` t2    ON t1.offer_id = t2.id
JOIN `company` t3  ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid
AND t3.status IN (4, 6)
GROUP BY t1.offer_id
ORDER BY t1.type

UNION

SELECT t1.offer_id, t1.cpv_id, t1.type,
FROM `offer_cpv` t1
JOIN `offer` t2      ON t1.offer_id = t2.id
JOIN `company_2` t3  ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid
AND t3.status IN (4, 6)
GROUP BY t1.offer_id

ORDER BY t1.type

SELECT t1.offer_id, t1.cpv_id, t1.type,
FROM `offer_cpv` t1
JOIN `offer` t2    ON t1.offer_id = t2.id
JOIN `company` t3  ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid
AND t3.status IN (4, 6)
GROUP BY t1.offer_id

UNION

SELECT t1.offer_id, t1.cpv_id, t1.type,
FROM `offer_cpv` t1
JOIN `offer` t2      ON t1.offer_id = t2.id
JOIN `company_2` t3  ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid
AND t3.status IN (4, 6)
GROUP BY t1.offer_id

ORDER BY t1.type

我可以以某种方式执行此UNION,但按类型排序结果。我按类型排序,因为我需要得到这样的输出:

<h2> Results of type 1 from both tables: </h2>
<div> Result 1 from **first** table </div>
<div> Result 2 from first table </div>
<div> Result 1 from **second** table </div>
<div> Result 2 from second table </div>
<h2> Results of type 2 from both tables: </h2>
<div> Result 1 from **first** table </div>
<div> Result 2 from first table </div>
<div> Result 1 from **second** table </div>
<div> Result 2 from second table </div>

稍后我将在ORDER BY子句中添加一个列:t1.rank,所以我可以先按类型排序,然后按排名排序!

2 个答案:

答案 0 :(得分:1)

您只能在整个UNION上订购。将t1.type的第一个ORDER BY别名删除为其他内容,例如&#34; mytype&#34;。然后将第二个ORDER BY更改为ORDER BY mytype

见这里:

SQL Query - Using Order By in UNION

答案 1 :(得分:1)

来自MySQL manual

  

这种ORDER BY不能使用包含a的列引用   表名(即tbl_name.col_name格式的名称)。代替,   在第一个SELECT语句中提供列别名并引用   ORDER BY中的别名。 (或者,请参阅中的列   ORDER BY使用其列位置。但是,使用列位置   不推荐使用。)

所以基本上你需要(i)为你需要在第一个查询中排序的列创建别名(ii)使用ORDER BY子句中的别名:

SELECT t1.offer_id, t1.cpv_id, t1.type AS type_column --, t1.rank as rank_column
FROM `offer_cpv` t1
JOIN `offer` t2 ON t1.offer_id = t2.id
JOIN `company` t3 ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid AND t3.status IN (4, 6)
GROUP BY t1.offer_id

UNION

SELECT t1.offer_id, t1.cpv_id, t1.type --, t1.rank
FROM `offer_cpv` t1
JOIN `offer` t2 ON t1.offer_id = t2.id
JOIN `company_2` t3 ON t2.cmpid = t3.id
WHERE t1.cpv_id = :cpvid AND t3.status IN (4, 6)
GROUP BY t1.offer_id

ORDER BY type_column --, rank_column