本文介绍了限制SQL JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制以下SQL语句。

I am trying to limit the following SQL statement.

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

我想要做的是限制父'行。 IE。如果我做一个LIMIT 1,我将只收到一个费用项,但仍然得到所有与之相关的交易。

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.

如何实现?

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

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

推荐答案

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

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

select * from expense, transaction where expense_id = transaction_expense_id



现在,如果你想应用一个限制,你可以这样做: / p>

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)

这样做你想要什么?很明显,你需要谨慎对待你的费用表将要回来的顺序,所以你可能想使用ORDER BY。

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.

编辑:鉴于MySQL的限制在下面的注释中,也许这将工作:

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;

这篇关于限制SQL JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 19:51