MySQL JOIN 在连接表上使用 LIMIT 1
我想连接两个表,但 table1 上的每条记录只能获取 table2 的 1 条记录
例如:
SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN products AS p ON c.id = p.category_id
这将获取 products
中的所有记录,这不是我想要的。我想要每个类别 1 个[第一个]产品(我在产品字段中有一个 sort
列)。
我该如何去做呢?
I want to join two tables, but only get 1 record of table2 per record on table1
For example:
SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN products AS p ON c.id = p.category_id
This would get me all records in products
, which is not what I want. I want 1 [the first] product per category (I have a sort
column in the products field).
How do I go about doing that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
我更喜欢类似问题中描述的另一种方法: https://stackoverflow.com/a/11885521/2215679
这种方法更好,尤其是在您需要在 SELECT 中显示多个字段的情况下。为了避免
错误代码:1241。操作数应包含 1 列
或对每列进行双子选择。对于您的情况,查询应该如下所示(此查询也适用于 PostgresQL,而且速度相当快,请参阅下面的更新):
这是最快的查询。使用这个。
PS。我对该查询与此处提出的其他查询进行了性能测试,该查询是迄今为止最好的选择!
更新(2022-07-20,PostgresSQL)
我已经有一段时间没有使用 mySQL 了,所以,我决定测试我的解决方案的性能(实际上它在 MySQL 和 PostgresSQL 中都能完美运行) )以及 @Gravy 在 PostgresQL v.12.9 中提供的解决方案。
为此,我决定创建一个包含 100 个类别 和 100000 个产品 的虚拟表和数据。您可以在这个要点上查看代码
我在上面运行了查询,只花了13毫秒运行。
在我稍微修改(对于 postgres)来自 @Gravy 的查询后:
这很慢,不要使用它!
并运行它。
在我的机器上花费了超过150ms。这>慢了10倍。
为了捍卫@gravy的解决方案,我同意n+1问题。但是,在这种特殊情况下,产品的数量通常比类别的数量多得多。因此,运行每个类别比运行每个产品(如 @Gravy 的查询)要便宜得多。
顺便说一句,如果你的表有 100 万个产品,100 个类别,我的查询速度还是一样的(9-17ms 之间),但是 [@Gravy] 的查询需要超过2 秒运行
在简历中,此刻,我的查询是当前任务的性能最佳且最佳的解决方案。
请随意发表评论。
I like more another approach described in a similar question: https://stackoverflow.com/a/11885521/2215679
This approach is better especially in case if you need to show more than one field in SELECT. To avoid
Error Code: 1241. Operand should contain 1 column(s)
or double sub-select for each column.For your situation the Query should looks like (this query also will work in PostgresQL and it is pretty fast, see my update below):
This is the fastest query. Use this one.
PS. I did the performance test of the query vs other proposed here, and this query is the best option yet!
UPDATE (2022-07-20, PostgresSQL)
I'm not working with mySQL for a while already, so, I decided to test the performance of my solution (which actually works perfect in both MySQL and PostgresQL) with solution provided by @Gravy in PostgresQL v.12.9.
For that I decided to create a dummy tables and data with 100 categories and 100000 products. You can check the code on this gist
I run my query above and it took only 13ms to run.
After I slightly modified (for postgres) the query from @Gravy:
This is slow, do not use it!
and run it too.
It took more than 150ms in my machine. Which is >10x times slower.
In defense of @gravy's solution, I agree with n+1 problem. But, in this particular case, usually the number of products is way larger than categories. So, running through each category is way less expensive than running through each product as in @Gravy's query.
By the way, if your table has 1mln products with 100 categories, the speed of my query is still the same (between 9-17ms), but the query from [@Gravy] takes more than 2 seconds to run
In resume, at this moment, my query is the most performant and optimal solution for the current task.
Feel free to comment.
@goggin13 接受的答案看起来是错误的。迄今为止提供的其他解决方案也可以工作,但会遇到 n+1 问题,因此会受到性能影响。
n+1问题:如果有100个类别,那么我们必须执行1次选择来获取类别,然后对于返回的100个类别中的每一个,我们都需要执行一次选择来获取该类别中的产品。因此将执行 101 次 SELECT 查询。
我的替代解决方案解决了 n+1 问题,因此性能应该显着提高,因为只执行 2 个选择。
Accepted answer by @goggin13 looks wrong. Other solutions provided to-date will work, but suffer from the n+1 problem and as such, suffer a performance hit.
n+1 problem: If there are 100 categories, then we would have to do 1 select to get the categories, then for each of the 100 categories returned, we would need to do a select to get the products in that category. So 101 SELECT queries would be performed.
My alternative solution solves the n+1 problem and consequently should be significantly more performant as only 2 selects are being performed.
这将返回产品中的第一个数据(等于限制 1)
This will return the first data in products (equals limit 1)
这又如何呢?
What about this?
With 子句就可以解决问题。像这样的东西:
The With clause would do the trick. Something like this:
在子查询中使用 MIN 或 MAX 将使查询运行得更快。
Using MIN or MAX in a subquery will make your query run much faster.
假设您希望在
sort
列中获得具有MIN()
imial 值的乘积,它看起来像这样。Assuming you want product with
MIN()
imial value insort
column, it would look something like this.另一个包含 3 个嵌套表的示例:
1/ 用户
2/ 用户角色公司
3/ Companie
Another example with 3 nested tables:
1/ User
2/ UserRoleCompanie
3/ Companie
在我看来,这是最好的答案(使其具有普遍性):
In my opinion, this is the best answer (making it general):
使用 postgres 时,您可以使用
DISTINCT ON
语法来限制从任一表返回的列数。以下是代码示例:
SELECT c.id, c.title, p.id AS Product_id, p.title
来自类别 AS c
加入 (
选择不同的 ON(p1.id) id、p1.title、p1.category_id
来自产品 p1
) p ON (c.id = p.category_id)
诀窍是不要直接连接多次出现 id 的表,而是首先创建一个每个 id 仅出现一次的表
When using postgres you can use the
DISTINCT ON
syntex to limit the number of columns returned from either table.Here is a sample of the code:
SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN (
SELECT DISTINCT ON(p1.id) id, p1.title, p1.category_id
FROM products p1
) p ON (c.id = p.category_id)
The trick is not to join directly on the table with multiple occurrences of the id, rather, first create a table with only a single occurrence for each id
将表格替换为您的表格:
Replace the tables with yours:
我会尝试这样的事情:
I would try something like this: