2015-10-20 101 views
1

我有两个表,我需要一个(左/右/内)加入两个日期字段。MySQL:问题与JOIN ON时间戳和日期

transactions表具有时间戳数据类型。 (Adminer的方式是我可以用“人格”来读取数据,而不是数量,就像你注意到的那样)。

另一个calendar表的数据类型为date

我要疯了试图cast/convert第一个timestampdate没有成功。 JOIN根本不是JOIN,就像两个数据是不同的类型。

SELECT * 
FROM transactions 
RIGHT JOIN calendar ON calendar.day_date = DATE(transactions.dateTransaction) 

我在calendartransactions和100 2倍的值,所以我很期待100点的记录 - 98 NULL和2填充。

当然,这不也改变:

SELECT * 
FROM transactions 
LEFT JOIN calendar ON calendar.day_date = DATE(transactions.dateTransaction) 

,或者还带有双DATE

SELECT * 
FROM transactions 
LEFT JOIN calendar ON DATE(calendar.day_date) = DATE(transactions.dateTransaction) 

或者也:

SELECT * 
    FROM calendar c 
    RIGHT JOIN transactions t ON c.day_date = DATE(t.dateTransaction) 

SELECT * 
    FROM calendar c 
    LEFT JOIN transactions t ON c.day_date = DATE(t.dateTransaction) 

我只获得2笔交易记录,我预计约100(100日历)。或者也可以使用FROM_UNIXTIME

transactions表模式:

CREATE TABLE `transactions` 
( `idTransactions` int(11) NOT NULL AUTO_INCREMENT, 
    `dateTransaction` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (`idTransactions`), 
    KEY `index_dateTransaction` (`dateTransaction`) USING BTREE 
) ENGINE=MyISAM AUTO_INCREMENT=155731 DEFAULT CHARSET=utf8 

calendar表模式

CREATE TABLE `calendar` 
( `day_date` date DEFAULT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 
+1

*我要疯投/第一时间戳记转换为数据*什么你的表列类型?首先发布您的架构 – Alex

+0

您是否尝试将calendar.day_date投射到日期?又名'DATE(calendar.day_date)'这也会有问题。 timestamp字段在特定日期有多个记录时会发生什么?它会给你多条记录 –

+0

@Alex添加了模式 – sineverba

回答

0

一个MySQL时间戳不一样的一个UNIX时间戳,它与特定的附加行为DATETIME列。您可以读取数据,因为它是日期时间值,不是因为发生了一些魔术转换。现在,如果您的其他列只是DATE数据类型,那么它们将不匹配:DATE <> DATETIME,加入它们意味着将其中一个转换为与另一个类型相同的类型,就像您在这些查询中所做的那样。

所以你真正的问题是你在建立查询的方式:如果你想使用的任何交易,那么所有压延:

SELECT * 
    FROM calendar c 
    LEFT JOIN transactions t ON c.day_date = DATE(t.dateTransaction) 

TIMESTAMP定义:https://dev.mysql.com/doc/refman/5.1/en/datetime.html

DATE()的定义:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date

+0

感谢您的回答,但通过您的查询,我仅获得交易中的2条记录。我错过了日历中的其他98/100。 – sineverba

+0

我确实尝试过您的QUERY。无论是用LEFT还是RIGHT加入,我都只能得到2笔交易记录。我认为问题是在转换... – sineverba

+0

@sineverba我认为问题是在数据,发布一些证据,如数据样本或截图。 – Alex

0

我能猜到你发出的问题的唯一方法是:你需要FULL OUTER JOIN这不是由mysql提供的。

但有一个小窍门: https://stackoverflow.com/a/4796911/4421474

所以我的猜测是:

http://sqlfiddle.com/#!9/9aa42d/4

SELECT `transactions`.*, 
    `calendar`.* 
FROM `transactions` 
LEFT JOIN `calendar` 
ON `calendar`.`day_date` = DATE(`transactions`.`dateTransaction`) 
UNION 
SELECT `transactions`.*, 
    `calendar`.* 
FROM `transactions` 
RIGHT JOIN `calendar` 
ON `calendar`.`day_date` = DATE(`transactions`.`dateTransaction`);