MySql:左连接用户表,事务表返回几行

时间:2014-11-08 20:18:24

标签: php mysql left-join

  • 我有2个表:users和paypal_transactions
  • 对于每个用户,我们都有一个id(在paypal_transactions表中名为user_id)
  • 用户可能有几个paypal_transactions。关系一对多
  • 我在查询时需要获取最新的交易ID(按date_dt DESC排序)

我当前的查询:

SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction` ON (`User`.`id` = `Transaction`.`user_id`)
ORDER BY `User`.`id` DESC
LIMIT 500

目前每个用户只有一个事务,它运行正常。 BTW有很多交易我还是从paypal_transactions表中获得第一个条目(最老的,但我想从现在起最新的。)

我做了很多尝试,没有成功。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你走了:

SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN (SELECT user_id, MAX(date_dt) AS max_date
            FROM `pronostics_framework`.paypal_transactions
            GROUP BY user_id) AS max_trans 
    ON User.id = max_trans.user_id
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction` 
    ON (max_trans.user_id = `Transaction`.`user_id` AND max_trans.max_date = Transation.date_dt)
ORDER BY `User`.`id` DESC
LIMIT 500

另一种方式,基于Retrieving the last record in each group第一个答案中的第一个查询:

SELECT `Transaction`.*, `User`.*, `Tipster`.`username`
FROM `pronostics_framework`.`users` AS `User`
LEFT JOIN `pronostics_framework`.`users` AS `Tipster` ON (`User`.`tipster_id` = `Tipster`.`id`)
LEFT JOIN `pronostics_framework`.`paypal_transactions` AS `Transaction` ON Transaction.user_id = User.id
LEFT JOIN `pronostics_framework`.paypal_transactions AS Transactions1 
    ON Transactions1.user_id = Transactions.user_id AND Transactions1.user_id > Transactions.user_id
WHERE Transactions1.user_id IS NULL
ORDER BY `User`.`id` DESC
LIMIT 500