LIMITing an SQL JOIN

一笑奈何 提交于 2019-11-27 14:31:33

问题


I am trying to limit the following SQL statement.

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

What I want to do, is limit the number of 'parent' rows. IE. if I do a LIMIT 1, I would receive only one expense item, but still get all transactions associated with it.

How would this be achieved?

At this stage, if I do LIMIT 1, I get one expense, and only one transaction.


回答1:


So assuming we can exclude the user table, it could be rewritten as:

select * from expense, transaction where expense_id = transaction_expense_id

Now if you want to apply a limit, you could do it like this:

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

Would that do what you wanted? Obviously you need to be cautious about what order your expense_ids are going to come back in, so you probably want to use ORDER BY whatever.

Edit: Given the MySQL limitation described in your comment below, maybe this will work:

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

Ben




回答2:


You'll have to specify which expense item you want to get. The most expensive? The newest? Then join against a subquery that returns only that:

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



回答3:


Since upgrading the SQL server is not an option, I may end up doing two queries.

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


来源:https://stackoverflow.com/questions/494974/limiting-an-sql-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!