MySql 左连接在几个regs上
我有这个 table1
idproduct(PK) | date_to_go
1 2010-01-18
2 2010-02-01
3 2010-02-21
4 2010-02-03
和另一个 table2 控制 date_to_go 更新
id | idproduct(FK) | prev_date_to_go | date_to_go | update_date
1 1 2010-01-01 2010-01-05 2009-12-01
2 1 2010-01-05 2010-01-10 2009-12-20
3 1 2010-01-10 2010-01-18 2009-12-20
4 3 2010-01-20 2010-02-03 2010-01-05
所以,在这个例子中,对于 table1.idproduct #1 2010-01-18 是实际的 date_to_go 和 2010-01-01 (table2.prev_date_to_go,第一个 reg)是原始的预计出发日期。
使用此查询
select v.idproduct, v.date_to_go, p.prev_date_to_go original_date_to_go
from table1 v
left join produto_datas p on p.idproduto = v.idproduto
group by (v.idproduto)
order by v.idproduto
我可以假设original_date_to_go将是table2的第一个相关reg吗?
idproduct | date_to_go | original_date_to_go
1 2010-01-18 2010-01-01
2 2010-02-01 NULL
3 2010-02-21 2010-01-20
4 2010-02-03 NULL
I have this table1
idproduct(PK) | date_to_go
1 2010-01-18
2 2010-02-01
3 2010-02-21
4 2010-02-03
and this other table2 that controls date_to_go updates
id | idproduct(FK) | prev_date_to_go | date_to_go | update_date
1 1 2010-01-01 2010-01-05 2009-12-01
2 1 2010-01-05 2010-01-10 2009-12-20
3 1 2010-01-10 2010-01-18 2009-12-20
4 3 2010-01-20 2010-02-03 2010-01-05
So, in this example, for table1.idproduct #1 2010-01-18 is the actual date_to_go and 2010-01-01 (table2.prev_date_to_go, first reg) is the original date_to_go .
using this query
select v.idproduct, v.date_to_go, p.prev_date_to_go original_date_to_go
from table1 v
left join produto_datas p on p.idproduto = v.idproduto
group by (v.idproduto)
order by v.idproduto
can I assume that original_date_to_go will be the first related reg of table2?
idproduct | date_to_go | original_date_to_go
1 2010-01-18 2010-01-01
2 2010-02-01 NULL
3 2010-02-21 2010-01-20
4 2010-02-03 NULL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您不能假设您始终会从第一行获取
prev_date_to_go
的值。当您选择的列未在 GROUP BY 中列出时,您可以返回的值可能是任何行中的值。请参阅 MySQL 文档 GROUP BY 和 HAVING with Hidden专栏了解更多信息:No, you cannot assume that you will always get the value of
prev_date_to_go
from the first row. When you select a column that isn't listed in your GROUP BY, the values you could get back could be the value from any row. See the MySQL documentation GROUP BY and HAVING with Hidden Columns for more information:好吧,我使用了子查询。
Well, I used a subquery.