How to limit results of a LEFT JOIN(如何限制 LEFT JOIN 的结果)
问题描述
以两个表为例:tbl_product
和 tbl_transaction
.tbl_product
列出产品详细信息,包括名称和 ID,而 tbl_transaction
列出涉及产品的交易并包括日期、产品 ID、客户等.
Take the case of two tables: tbl_product
and tbl_transaction
.
tbl_product
lists product details including names and ids while tbl_transaction
lists transactions involving the products and includes dates, product-ids, customers etc.
我需要显示一个网页,其中显示 10 种产品以及每种产品的最近 5 笔交易.到目前为止,没有 LEFT JOIN
查询似乎工作,如果 mysql 可以允许 tx.product_id=ta.product_id
部分(失败 where 子句"中的未知列ta.product_id":[ERROR:1054]).
I need to display a web-page showing 10 products and for each product, the last 5 transactions. So far, no LEFT JOIN
query seems to work and the subquery below would have worked if mysql could allow the tx.product_id=ta.product_id
part (fails with Unknown column 'ta.product_id' in 'where clause': [ERROR:1054]).
SELECT
ta.product_id,
ta.product_name,
tb.transaction_date
FROM tbl_product ta
LEFT JOIN (SELECT tx.transaction_date FROM tbl_transaction tx WHERE tx.product_id=ta.product_id LIMIT 5) tb
LIMIT 10
有没有办法实现我需要的列表无需在循环中使用多个查询?
Is there a way to achieve the listing I need without using multiple queries in a loop?
这正是我需要的 MySQL:
This is exactly what I need from MySQL:
SELECT ta.product_id, ta.product_name, tb.transaction_date ...
FROM tbl_product ta
LEFT JOIN tbl_transaction tb ON (tb.product_id=ta.product_id LIMIT 5)
LIMIT 10
当然这是非法的,但我真的希望不是这样!
Of course this is illegal, but I really wish it wasn't!
推荐答案
这就是排名函数非常有用的地方.不幸的是,MySQL 还不支持它们.相反,您可以尝试以下方法.
This is where ranking functions would be very useful. Unfortunately, MySQL does not yet support them. Instead, you can try something like the following.
Select ta.product_id, ta.product_name
, tb.transaction_date
From tbl_product As ta
Left Join (
Select tx1.product_id, tx1.transaction_id, tx1.transaction_date
, (Select Count(*)
From tbl_transaction As tx2
Where tx2.product_id = tx1.product_id
And tx2.transaction_id < tx1.transaction_id) As [Rank]
From tbl_transaction As tx1
) as tb
On tb.product_id = ta.product_id
And tb.[rank] <= 4
Limit 10
这篇关于如何限制 LEFT JOIN 的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何限制 LEFT JOIN 的结果


基础教程推荐
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01