2014-01-06 173 views
-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] 

我不知道如何編寫正確的查詢這方面的任何變種例。

任何想法,將不勝感激。謝謝。

回答

2
SELECT u.id, u.username, up.email, 
     SUM(IF(p.direction = 'payin', p.amount, 0)) AS payin, 
     SUM(IF(p.direction = 'payout', p.amount, 0)) AS payout, 
     SUM(p.direction = 'payin') AS payin_count, 
     MAX(IF(p.direction = 'payin', p.time, 0)) AS payin_maxtime 
FROM users AS u 
JOIN userprofiles AS up ON u.id = up.user_id 
JOIN payments AS p ON u.id = p.user_id 
GROUP BY u.id 
+3

您可能還需要按用戶名和電子郵件進行分組。 –

+3

MySQL通常不需要這樣做。 – Barmar

+0

@Barmar,你可以給我一個關於「MySQL通常不需要這個」的好文章的鏈接,我想深入瞭解這個問題。謝謝。 –