sqlite join问题

时间:2014-05-27 17:47:20

标签: sqlite

这是我的数据库架构:

CREATE TABLE orders (
    transaction_id integer primary key autoincrement,
    total_price integer not null
);
CREATE TABLE order_items (
    transaction_id integer REFERENCES orders(transaction_id),
    SKU integer not null,
    product_name text not null,
    unit_price integer not null,
    quantity integer not null
);

我要做的是从orders表中获取最后一行,并将该transaction_id与order_items表中包含相同transaction_id的所有项匹配

我试过这个sqlite查询无济于事:

sqlite> SELECT orders.transaction_id, orders.total_price
   ...> FROM orders
   ...> ORDER BY transaction_id DESC LIMIT 1
   ...> WHERE orders.transaction_id = order_items.transaction_id;

1 个答案:

答案 0 :(得分:1)

ORDER BY必须在WHERE之后。 但是,LIMIT 1只会返回一条记录。

您无法在order_items中访问列,而无需在FROM子句中提及它。

您应该使用子查询过滤事务:

SELECT *
FROM orders
JOIN order_items USING (transaction_id)
WHERE orders.transaction_id = (SELECT MAX(transaction_id)
                               FROM orders)