我很难想到如何将数据从一个表中连接到BASE表......但仅限于从基表中的第一行...是甚至可能的吗?mysql左连接仅从基表第一行
例如:
TABLE1
item_id | insert_datetime | value
---------------------------------------
2 | 1/1/2014 12:54:05 | 65
2 | 1/1/2014 12:57:05 | 65
3 | 8/7/2014 10:01:47 | 87
3 | 9/8/2014 09:37:21 | 33
3 | 9/8/2014 09:42:21 | 33
4 | 2/9/2014 15:22:01 | 58
TABLE2
item_id | drop_datetime | value
---------------------------------------
2 | 1/1/2014 00:00:00 | 65
3 | 9/8/2014 00:00:00 | 33
(由ID,日期[不日期时间],值左接合)我需要做的像这样:
SELECT t1.item_id
, t1.insert_datetime as inserted
, t1.value as ins_value
##
, t2.drop_datetime as cancelled
, t2.value as cld_value
##
FROM table1 t1
##
LEFT JOIN table2 t2
ON t2.item_id = t1.item_id
AND date(t2.drop_datetime) = date(t1.insert_datetime)
AND t1.value = t2.value
##
WHERE 1=1
因此,这意味着我需要得到哪些值被取消......但在情况下ITEM_ID = 2出现了以下情况:
项目被运在2014年1月1日12时54分05秒(值为65)...它被取消(T2中的第一行),由于参数错误而被重新发送1/1/2014 12:57:05具有相同的值
我得到的item_id = 2是:
item_id | inserted | ins_value | cancelled | cld_value
-----------------------------------------------------------------------------
2 | 1/1/2014 12:54:05 | 65 | 1/1/2014 00:00:00 | 65
2 | 1/1/2014 12:57:05 | 65 | 1/1/2014 00:00:00 | 65
但我NEED得到这样的:因为在现实中
item_id | inserted | ins_value | cancelled | cld_value
-----------------------------------------------------------------------------
2 | 1/1/2014 12:54:05 | 65 | 1/1/2014 00:00:00 | 65
2 | 1/1/2014 12:57:05 | 65 | |
,只是第一抵消了。是有可能得到这样的结果在MySQL?
注:和项目也可以,可惜的是,在一小时内取消两个或threetime
**EDIT 1**
如果有帮助......所有数据都在一个表中与SHIP的症状(1)或CANCLED(2)
源表
id | item_id | insert_datetime | value | symptom
-----------------------------------------------------------
1 | 2 | 1/1/2014 12:54:05 | 65 | 1
2 | 2 | 1/1/2014 00:00:00 | 65 | 2
3 | 2 | 1/1/2014 12:57:05 | 65 | 1
4 | 3 | 8/7/2014 10:01:47 | 87 | 1
5 | 3 | 9/8/2014 09:37:21 | 33 | 1
6 | 3 | 9/8/2014 00:00:00 | 33 | 2
7 | 3 | 9/8/2014 09:42:21 | 33 | 1
8 | 4 | 2/9/2014 15:22:01 | 58 | 1
这会有帮助吗?
**POSSIBLE SOLUTION**
看来,这个工程确定:
SELECT t1.item_id
, t1.insert_datetime as inserted
, t1.value as ins_value
##
, t2.drop_datetime as cancelled
, t2.value as cld_value
##
FROM table1 t1
##
LEFT JOIN table2 t2
ON t2.item_id = t1.item_id
AND date(t2.drop_datetime) = date(t1.insert_datetime)
AND t1.value = t2.value
AND t1.id < t2.id ## <- this should do the trick
##
WHERE 1=1
你怎么知道的只有第一个被取消了?我认为数据模型是错误的。 table2中的itemid应指向一个唯一的ID,以便知道哪一个被取消。目前,没有什么好的方法可以确定,并且您需要猜测业务规则并编写一个不必要的复杂查询来解决该问题。 – GolezTrol 2014-12-04 14:00:39
我不知道这个......我想......但它应该是第二个......实际上,没关系..我需要看看有多少物品被取消,其中有多少不是...... 。但详细:(我同意数据模型是错误的,但我没有机会改变它:( – 2014-12-04 14:04:17
我已经添加了更多关于原始结构的信息..也许它会帮助 – 2014-12-04 14:14:35