【发布时间】:2015-05-14 11:06:42
【问题描述】:
如果我不做 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(而且我必须),我的查询会中断:
“订单子句”中的未知列“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,这样我就可以先按类型排序,然后也按排名!
【问题讨论】:
-
你需要一个外部查询...
select x.offer_id, x.cpv_id, x.type from ( here is the union query)x order by x.type
标签: php mysql sql union sql-order-by