【问题标题】:Using Union All and Order By in MySQL在 MySQL 中使用 Union All 和 Order By
【发布时间】:2012-10-15 09:24:12
【问题描述】:

我有 2 张桌子:

create table advertised_products(id int,title varchar(99),timestamp timestamp);
insert advertised_products select 1,'t1',curdate();

create table wanted_products(id int,title varchar(99),timestamp timestamp);
insert wanted_products select 1,'t1',now();

我正在使用此查询来获取记录:

(
SELECT 
    ap.*,
    'advertised'  as type 
FROM advertised_products as ap
)
union all
(
SELECT 
    wp.*,
    'wanted' as type 
FROM wanted_products as wp
)
ORDER BY timestamp desc limit 3

但它给出了错误:

订单子句中的“时间戳”列不明确

我该如何排序?

【问题讨论】:

  • 您使用的是什么版本的 MySQL?您的查询没有错误,并且在这里运行良好(版本5.5.10)。

标签: mysql sorting union-all


【解决方案1】:

将其包装在子查询中。

SELECT s.*
FROM
    (
        SELECT  ap.*, 'advertised'  as type 
        FROM advertised_products as ap
          union all
        SELECT  wp.*, 'wanted' as type 
        FROM wanted_products as wp
    ) s
ORDER BY s.timestamp desc 
limit 3

【讨论】:

【解决方案2】:

错误就在这里,

 "ORDER BY timestamp desc limit 3"

当您组合两个表时,查询必须知道您在哪个表中使用了哪些字段。显然您在“orderby”子句中缺少表引用

提及表名/表名的别名,如下所示

 "ORDER BY your_table_name.timestamp desc limit 3"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2010-09-26
    • 1970-01-01
    • 2016-09-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多