开发者

greatest n per group multi table

开发者 https://www.devze.com 2023-03-15 12:21 出处:网络
i know there is heaps of this same question but im having trouble making it work on multiple table joins. i have 3 tables

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 transa开发者_Go百科ction 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()
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号