3

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

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、金额、payate、descr

这是我使用获取该信息的选择语句:-

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)。

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

4

2 回答 2

1

听起来您想使用 MySQLGROUP 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)
于 2012-10-03T14:15:17.373 回答
1

你可以在桌子JOIN上两次。transactions第一次加入获取max()每个的日期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

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

select c.conid,
  s.serviceName,
  c.cid,
  c.term,
  c.monthly_charge,
  c.start_date,
  c.expiry_date,
  c.next_PayDate,
  c.status,
  t3.amount,
  t3.paidate,
  t3.descr
FROM servicetype s 
LEFT JOIN contract c 
  on s.sid = c.servName
LEFT JOIN
(
  SELECT max(paidate) paidate, conid, max(tid) tid
  FROM transactions t
  GROUP BY conid
) t1
  on c.conid = t1.conid
LEFT JOIN transactions t3
  on t1.conid = t3.conid
  and t1.paidate = t3.paidate
  and t1.tid = t3.tid
where c.cid = 4
  and c.status = 1
GROUP BY c.conid;

请参阅带有演示的 SQL Fiddle

于 2012-10-03T14:16:31.967 回答