简体   繁体   中英

Having SQL Query not group results

I have a sql query that joins a few tables by user_id , the problem is is that I would like to see all the data from these tables.

At the moment I am querying the user table and the payment table and joining them based on the user_id .

I seem to only getting one result per user_id, now I know this it what is meant to happen but how (if possible), would I be able to show all the data from the payment table (ie I want to see multiple user ids that show the various payments that user has made).

I am currently using a left join, I'm thinking this may be the issue but switching it still isn't showing the results I am looking for.

This i my current join:

from user u 
left join u_subscription us 
on u.user_id = us.user_id 
left join u_detail ud 
on u.user_id = ud.user_id

Any help would be hugely appreciated.

Thanks in advance

Nad

Full sql query:

select u.user_id as 'prop:User id', u.user_username as 'prop:username', u.user_email as 'Identity',u.user_created as 'Timestamp', us.user_subscription_expires as 'prop:Expires on', us.user_subscription_payment_provider as 'prop:Payment provider', us.user_subscription_modified, ud.user_detail_signup_country_iso3 as 'prop:Country'

from user u
left outer join user_subscription us
on u.user_id = us.user_subscription_user_id
left outer join user_detail ud
on u.user_id = ud.user_detail_user_id

I suggest using another method:

select
   'your selected columns'
from
   user u,
   u_subscription us,
   u_detail ud
where 
   u.user_id = us.user_id and
   u.user_id = ud.user_id

this works just like the join method but for me, this method makes the query cleaner and easier to understand.. hope it helped!

Since you are specifically looking for something of details / payments, use THAT table as the basis of the query, then join to the users table as the detail would only exist based on a user... However, you can left-join to the subscription if that is conditional. Something like

select
      u.*,
      ud.*,
      us.*
   from
      u_detail ud
         join user u
            on ud.user_id = u.user_id
         left join u_subscription us
            on ud.user_id = us.user_id

Since the userID would be the same from user detail to the user table, just use the same for joining to the subscription table. I normally would not use "*" for fields, but pick what you want from it.

I find no flaws in your query. It should be working as expected.

I'm suspecting there is no more than one row per user in the subscription and detail tables. That's why your left join produces exactly one row per user (if it was an inner join, it would produce at most one row per user).

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