Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIMITing an SQL JOIN

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.

like image 721
Thomas R Avatar asked Jan 30 '09 09:01

Thomas R


People also ask

How do I reduce the number of joins in SQL?

Create indexes, concretely use compound indexes, for instance, start creating a compound index for event and groups: on table events create one for (event id, group id). then, on the group table create another one for the next relation (group id, local id). on local do the same with service, and so on...

How do I limit a selection in SQL?

The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the number of records returned based on a limit value. TIP: SELECT LIMIT is not supported in all SQL databases. For databases such as SQL Server or MSAccess, use the SELECT TOP statement to limit your results.

Is there a limit on number of joins?

There's no limit on the number of joins, otherwise it would throw an error almost immediately. They are all Table Values Functions.

How do I limit in SQL Server?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.


1 Answers

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

like image 111
Ben Avatar answered Sep 23 '22 17:09

Ben