从多个表MySql中获取数据?

时间:2014-01-06 14:58:52

标签: mysql sql

表格具有以下结构:

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]

我没有关于如何为此示例编写正确查询的任何变体。

任何想法都会受到赞赏。感谢。

1 个答案:

答案 0 :(得分: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