限制SQL JOIN

时间:2009-01-30 09:40:36

标签: sql database join sql-limit

我试图限制以下SQL语句。

SELECT expense.*, transaction.* FROM expense
INNER JOIN transaction ON expense_id = transaction_expense_id

我想做的是限制'父'行的数量。 IE浏览器。如果我做了LIMIT 1,我只会收到一个费用项目,但仍然可以获得与之相关的所有交易。

如何实现这一目标?

在这个阶段,如果我做LIMIT 1,我得到一笔费用,只有一笔交易。

4 个答案:

答案 0 :(得分:12)

因此,假设我们可以排除用户表,可以将其重写为:

select * from expense, transaction where expense_id = transaction_expense_id

现在,如果你想申请限额,你可以这样做:

select * from expense, transaction where expense_id = transaction_expense_id and 
  expense_id in (select expense_id from expense limit 1)

那会做你想要的吗?显然,您需要谨慎处理您的expense_ids将要返回的顺序,因此您可能希望使用ORDER BY。

编辑:鉴于下面评论中描述的MySQL限制,可能会有效:

select * from (select id from expense order by WHATEVER limit 1) as t1, transaction where expense_id=transaction_expense_id;

答案 1 :(得分:7)

您必须指定要获得的费用项目。最昂贵的?最新的?然后加入一个仅返回的子查询:

SELECT
    expense.*, transaction.*, user.*
FROM
    (SELECT * FROM expense WHERE ...) AS expense
INNER JOIN
    transaction ON expense_id = transaction_expense_id

答案 2 :(得分:2)

由于无法升级SQL服务器,我最终可能会进行两次查询。

expenses = SELECT * FROM expense ... LIMIT x
foreach expenses as expense
    expense.transactions = SELECT * FROM transacion WHERE transaction_expense_id = expense.expense_id

答案 3 :(得分:0)

即使这很旧...在搜索中遇到此问题,并考虑到无法在子查询中使用限制,因此我想添加一些想法...

select e.expense_id, transaction.* 
from (select max(expense_id) from expense) e 
    inner join transaction t ON e.expense_id = t.transaction_expense_id

或者如果您想拥有expense中的所有列,而不仅仅是expense_id,则可以嵌套子查询。

select e.*, t.*
from (
     select e1.*
     from expense e1 inner join (select max(expense_id) from expense) e2
        on e1.expense_id = e2.expense_id
     ) e  inner join transaction t on e.expense_id = t.transaction_expense_id