简体   繁体   中英

greatest n per group multi table

i know there is heaps of this same question but im having trouble making it work on multiple table joins. i have 3 tables

userinfo

user_id | firstname | lastname

subnumbers

subnumber | fkuserid

transaction

transid | fksubnumber | expires | transdate

heres the part i have working

SELECT *
FROM (SELECT *
FROM subtransactions
WHERE Expires < now()
ORDER BY NewSubTrans DESC) AS s
GROUP BY FKSubNum

What i am trying to do is select all users with a subscription that is expired. to determine if a user is expired i pull the last transaction from the transaction table with thier sub number, the fk fields are the links to the other tables.

From your description, I don't think you need any group at all. Try it with just these two joins:

SELECT user_id, firstname, lastname
FROM
 userinfo
  JOIN subnumbers ON userinfo.user_id = subnumbers.fkuserid
  JOIN transaction ON subnumbers.subnumber = transaction.fksubnumber
WHERE transaction.expires < NOW()

EDIT If it returns multiple rows as suggested in comments below, use DISTINCT in the select list:

SELECT DISTINCT user_id, firstname, lastname
  -- etc...

This will get all user_ids

select distinct(user_id) from userinfo
join subnumbers on userinfo.user_id = subnumbers.fkuserid
join transaction on transaction.fksubnumber = subnumbers.subnumber
where transaction.expires < NOW()

To get full user data

select * from user where user_id in
(
select distinct(user_id) from userinfo
join subnumbers on userinfo.user_id = subnumbers.fkuserid
join transaction on transaction.fksubnumber = subnumbers.subnumber
where transaction.expires < NOW()
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM