-2
該表具有以下結構:從多個表MySql中獲取數據?
CREATE TABLE IF NOT EXISTS `payments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`direction` enum('payin','payout') NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL,
`time` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `dir` (`direction`),
KEY `user_id` (`user_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(64) NOT NULL,
`password` varchar(64) NOT NULL,
`created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`logins` int(10) unsigned NOT NULL DEFAULT '0',
`last_login` int(10) unsigned DEFAULT NULL,
`lock` tinyint(1) unsigned NOT NULL DEFAULT '0',
`refer` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_username` (`username`),
KEY `lock` (`lock`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `userprofiles` (
`user_id` int(10) unsigned NOT NULL,
`email` varchar(255) DEFAULT NULL,
`firstname` varchar(255) DEFAULT NULL,
`lastname` varchar(255) DEFAULT NULL,
`nick` varchar(255) DEFAULT NULL,
`birthday` timestamp NULL DEFAULT NULL,
`gender` enum('male','female') DEFAULT NULL,
`country` varchar(3) DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email` (`email`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
我想查詢的輸出與以下結構:
users.id,
users.username,
userprofiles.email,
[SUM OF AMOUNT WITH DIRECTION payin],
[SUM OF AMOUNT WITH DIRECTION payout],
[COUNT OF PAYMENTS WITH DIRECTION payin],
[MAX TIME OF PAYMENT WITH DIRECTION payin]
我不知道如何編寫正確的查詢這方面的任何變種例。
任何想法,將不勝感激。謝謝。
您可能還需要按用戶名和電子郵件進行分組。 –
MySQL通常不需要這樣做。 – Barmar
@Barmar,你可以給我一個關於「MySQL通常不需要這個」的好文章的鏈接,我想深入瞭解這個問題。謝謝。 –