从三个不同的表中选择最大值和其他值

时间:2012-10-03 14:10:55

标签: mysql

我有三个具有以下结构的表: -

CREATE TABLE `contract` (
  `conid` int(11) NOT NULL AUTO_INCREMENT,
  `servName` int(11) NOT NULL,
  `cid` int(11) NOT NULL,
  `term` int(11) DEFAULT NULL,
  `monthly_charge` double NOT NULL,
  `start_date` date NOT NULL,
  `expiry_Date` date NOT NULL,
  `next_PayDate` date DEFAULT NULL,
  `status` tinyint(4) NOT NULL,
  PRIMARY KEY (`conid`),
  UNIQUE KEY `servName` (`servName`,`cid`)
) 

CREATE TABLE `servicetype` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `serviceName` varchar(255) NOT NULL,
  PRIMARY KEY (`sid`)
) 

CREATE TABLE `transactions` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `conid` int(11) NOT NULL,
  `amount` double NOT NULL,
  `paidate` date NOT NULL,
  `descr` text NOT NULL,
  PRIMARY KEY (`tid`)
)

我想得到的是特定用户的最新交易,即: -

conid,serviceName,cid,term,monthly_charge,start_date,expiry_Date,next_PayDate,amount,paidate,descr

这是我使用获取信息的select语句: -

SELECT c.conid, serviceName, cid, term, monthly_charge, start_date, expiry_Date, next_PayDate, status, amount, paidate, descr
FROM servicetype s 
LEFT JOIN contract c on s.sid = c.servName 
LEFT JOIN transactions t ON c.conid=t.conid
WHERE cid = 4 AND status = 1

该声明有效,但它给了我所有属于cid 4的交易,而我想要显示的只是属于所述合约的最新交易(conid)。

提前感谢您的时间和精力。

2 个答案:

答案 0 :(得分:1)

听起来您希望使用MySQL GROUP BY按特定cid对所有结果进行分组,然后使用HAVING条件获取MAX()交易:

SELECT
    c.conid, serviceName, cid, term, monthly_charge, start_date, expiry_Date, next_PayDate, status, amount, paidate, descr
FROM servicetype s 
    LEFT JOIN contract c on s.sid = c.servName 
    LEFT JOIN transactions t ON c.conid=t.conid
WHERE
    cid = 4 AND status = 1

GROUP BY cid
HAVING t.paidate = MAX(t.paidate)

答案 1 :(得分:1)

您可以在JOIN表格上transactions两次。第一个联接获取每个max()的{​​{1}}日期,然后第二个联接将返回该最大事务的详细信息:

conid

根据您的评论编辑,查询应为:

select c.conid,
  s.serviceName,
  c.cid,
  c.term,
  c.monthly_charge,
  c.start_date,
  c.expiry_date,
  c.next_PayDate,
  c.status,
  t2.amount,
  t1.paidate,
  t2.descr
FROM servicetype s 
LEFT JOIN contract c 
  on s.sid = c.servName 
LEFT JOIN
(
  SELECT max(paidate) paidate, conid
  FROM transactions
  GROUP BY conid
) t1
  ON c.conid=t1.conid
LEFT JOIN transactions t2
  ON t1.paidate = t2.paidate
  AND t1.conid = t2.conid
WHERE c.cid = 4 
  AND c.status = 1

请参阅SQL Fiddle With Demo