4

我有 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

但它给出了错误:

order 子句中的列 'timestamp' 不明确

我该如何排序?

4

2 回答 2

3

将其包装在子查询中。

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
于 2012-10-15T09:25:55.797 回答
0

错误就在这里,

 "ORDER BY timestamp desc limit 3"

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

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

 "ORDER BY your_table_name.timestamp desc limit 3"
于 2012-10-15T09:32:21.093 回答