正确地从MySql表中获取数据

时间:2014-03-21 16:33:09

标签: jquery mysql join

有两个简单的表格。输出表的结构如下:
|日期|主持人|点击| Sum_Payin | Merchant_Id |

日期 - 唯一(每个日期的总和和计数)
主机 - Merchant_Id = 8的每个日期的唯一主机数量 点击次数 - 点击次数,即Merchant_Id = 8的每个日期上每个主机点击的总和 Sum_Payin - Merchant_Id = 8的每个日期的付款总和

如何在2014-03-01和2014-03-31之间正确选择查询?
我每天都需要数据。
谢谢你的建议!

CREATE TABLE IF NOT EXISTS `hosts` (
`date` date NOT NULL,
  `host` int(10) unsigned NOT NULL,
  `merchant_id` int(10) unsigned NOT NULL,
  `hits` int(10) unsigned NOT NULL,
  PRIMARY KEY (`date`,`host`),
  KEY `merchant_id` (`merchant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `hosts` (`date`, `host`, `merchant_id`, `hits`) VALUES
('2014-03-01', 2, 8, 3),
('2014-03-01', 4, 8, 2),
('2014-03-03', 5, 8, 5),
('2014-03-07', 6, 8, 1);

-- --------------------------------------------------------

CREATE TABLE IF NOT EXISTS `payments` (
`date` date NOT NULL,
  `customer_id` int(10) unsigned NOT NULL,
  `payin` decimal(10,2) unsigned NOT NULL,
  `merchant_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`date`,`customer_id`),
  KEY `merchant_id` (`merchant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `payments` (`date`, `customer_id`, `payin`, `merchant_id`) VALUES
('2014-03-01', 2, 200.00, 8),
('2014-03-02', 3, 300.00, 8),
('2014-03-06', 3, 100.00, 8),
('2014-03-07', 5, 250.00, 8);

2 个答案:

答案 0 :(得分:0)

查看此演示 SQLFiddle Demo result

查询

select hosts.date,
        hosts.host,
        hosts.hits,
        sum(payments.payin) as Sum_Payin,
        hosts.merchant_id 
        FROM hosts
        INNER JOIN payments ON 
        payments.merchant_id = hosts.merchant_id
        WHERE hosts.date BETWEEN '2014-03-01' AND '2014-03-31';

另一个演示如果您想获得此记录date明智地 check this demo jsFiddle

希望这对你有帮助!

答案 1 :(得分:0)

要从上面的答案中扩展你的评论:

SELECT hosts.date,
        hosts.host,
        hosts.hits,
        SUM(payments.payin) as Sum_Payin,
        hosts.merchant_id 
        FROM hosts
        INNER JOIN payments ON 
        payments.merchant_id = hosts.merchant_id
        WHERE hosts.date >= 2014-03-01
        AND hosts.date <= 2014-03-31
        GROUP BY hosts.date;