SQL query to find largest id for each user_id - mysql

I am currently querying from 4 different tables,
users, memberships_users, membership_levels, phone_area_code
From the users table, I would like to select
id
user_login,
user_email,
display_name
The memberships_users table contains a user_id column as well as an id column. The user_id column is not unique, and there are many repeating user ids.
From the memberships_users table, I would like to select
initial_payment,
billing_amount,
cycle_period,
cycle_number,
from the row with the largest id for each user_id
and
name from the membership_levels table and
meta_value from the phone_area_code table
which should all relate the id in the users table

This is basically pseudo-code of one way of getting what you want.
First, create a derived table of each user_id and the max(id) from the membership table. This will yield all distinct user_id's aligned with the associated max id from the membership. The next step is to join the two physical tables with the derived one to get the user and the associated membership record contain the max membership id.
NOTE : If your memberships_users table is on the large side then you will get better performance dropping the max_membership_id data into a temp table and adding appropriate indexes.
;WITH max_membership_id AS
(
SELECT user_id, max_id = MAX(id)
FROM memberships_users
GROUP BY user_id
)
SELECT
u.id, u.user_login, u.user_email, u.display_name,
mu.initial_payment, mu.billing_amount, mu.cycle_period, mu.cycle_number
FROM
users u
INNER JOIN max_membership_id mmi ON mmi.user_id = u.user_id
INNER JOIN memberships_users mu ON mu.id = mmi.max_id

Related

Finding Values of same ID from different table

I have 2 tables:
1.Users (This table contains all the information of users like name, Userid, mobileno)
2.Transaction (This table contains the information of all the transaction of a user)
But the UserID is same in both the tables
I have some filter conditions like:
[ TransactionType=1 AND status=1 and (RealCash>0 or Bonus>0 or Winning>0)] which i want to apply on Transaction table
once I applied the condition i will have some UserID
Now i want that the information of the users from the Users table that have the same UserID which i've obtained from above from the transaction table
How can i do that in MYSQL ?
use JOIN : https://www.mysqltutorial.org/mysql-join/
For example:
SELECT
u.name,
u.Userid,
u.mobileno,
t.TransactionType
FROM
Users u
INNER JOIN Transaction t ON t.Userid = c.Userid
WHERE t.TransactionType=1 AND t.status=1 and (t.RealCash>0 or t.Bonus>0 or t.Winning>0)
But read carefully about other join types (left, right, cross) as you may get different results.
SELECT
name, Userid, mobileno
FROM
Users
WHERE
UserID IN (SELECT
UserID
FROM
Transaction
WHERE
TransactionType=1 AND status=1 and (RealCash>0 or Bonus>0 or Winning>0);

Retrieve same column of a table for 2 different columns in another table

I have 2 tables "users" and "transactions". Users table contains userid ans name. Transactions table contains senderid, receiverid and amount. I want to get the names of both sender and receiver. Senderid and receiverid are foreign keys of users.userid
You need to join to the users table multiple times:
select s.name, r.name, t.amount
from transactions t
join users s on t.senderid = s.userid
join users r on t.senderid = r.userid
If there are user ids in the transactions table that does not exist in the users table, you'll need to use an outer join instead.

How to join on conditional tables

I have to maintain a database that has 3 different tables for their users (for different roles). Unfortunately, merging them is not allowed.
There is another table that logs their activity, and this table has two columns for identifying a specific user, one is userId, and the other is roleId. Now, when I want to list user activities for all users, then depending on the value in roleId, I would have to join each row with a different table.
If there was only one table with users, the query would be something like:
SELECT * FROM activity JOIN buyers ON activity.userId = buyers.id
So how would I expand on this query now, if I had 3 tables with users: buyers, sellers, and administrators; knowing that the roleId column in the activity table identifies either a buyer, a seller, or an administrator?
SELECT *, 'Buyer' as accountType FROM activity JOIN buyers b ON activity.userId = b.id
UNION
SELECT *, 'Seller' FROM activity JOIN sellers s ON activity.userId = s.id
UNION
SELECT *, 'Admin' FROM activity JOIN administrators a ON activity.userId = a.id
may consider writing the above as a view that way I could build on it as needed, given I can't change any existing table design.
may have to spell out specific table columns as well if buyer, seller, and admin have different columns. Given you've not provided the table structures, I'm assuming they are identical for this example purpose.
Just guessing here as to how roleId relates to the other tables.
SELECT * FROM activity JOIN buyers ON activity.userId = buyers.id
WHERE activity.roleId = 1
UNION SELECT * FROM activity JOIN sellers ON activity.userId = sellers.id
WHERE activity.roleId = 2
UNION SELECT * FROM activity JOIN administrators ON activity.userId = administrators.id
WHERE activity.roleId = 3

M:N relation an query

i've some problems with a specific mysql query an an specific construct.
There are 2 tables:
table users (id, username)
table groups (id, groupname)
these 2 tables are in an m:n relation, but there are 2 tables for that.
First in maps user to groups
table usertogroups (idmaster, idslave)
where idmaster is related to users.id and idslave is related groups.id
Second maps groups to users
table groupstouser (idmaster, idslave)
where idmaster is related to groups.id an idslave is related to users.id
Depend on the application it could not be changed.
Now i want to get all groups with the depending users in one query with the relation of both table, groupstouser and usertogroups.
I've tried al lot of statements, but if I take the second table in it doesn't work.
Any helpfull Ideas?
Use this as an inline view to get the data from both association tables :
((SELECT idmaster AS userid, idslave AS groupid FROM userstogroup)
UNION
(SELECT idslave AS userid, idmaster AS groupid FROM groupstouser)) all_associations
Then you can query like this :
SELECT groups.groupname, users.username
FROM groups
INNER JOIN ((SELECT idmaster AS userid, idslave AS groupid FROM userstogroup)
UNION
(SELECT idslave AS userid, idmaster AS groupid FROM groupstouser)) all_associations
ON groups.id = all_associations.groupid
INNER JOIN users
ON users.id = all_associations.userid
And here's an SQL Fiddle.
I am not sure, it might solve your problem:
(SELECT * FROM usertogroups WHERE idmaster=10)
UNION
(SELECT * FROM groupstouser WHERE idslave=10)
I think your database design is wrong.
When a user is assigned to a group only single table can be used for it. You must be saving duplicate records in both usertogroups and groupstouser.
Try to get your data from only single table.
SELECT * FROM usertogroups order by idslave
If I am wrong that you are not saving duplicate data in both the tables, then specify reason of having two tables

How do I get the values from one table based on the relationship specified in another?

I have a table called user_info which has a unique id and general information like title, firstname, lastname, number, etc..
I have another table useralias which has two columns; userid and aliasid.
At the moment I select * from user_info where timestamp > 'a timestamp'.
How can I also append to the results a duplicate of each user_info record for each useralias record in the alias table based on userid, keeping into account the timestamp.
Except I want to replace the userid with the alias id for these extra records, but return the rest of the details as if there were an exact copy of that user_info record except with a different id.
If you just want the aliases and not the original user id, then a simple join does what you want:
select ua.aliasid, <all columns from user that you want>
from user u join
useralias ua
on u.userid = ua.userid
If you want both the userids and the aliases, then you need to augment the table you are joining to:
select ua.aliasid, <all columns from user that you want>
from user u join
(select userid, aliasid
from ((select userid, aliasid
from useralias ua
)
union all
(select userid, userid as aliasid
from user
)
) t
) ua
on u.userid = ua.userid
This query creates a list of pairs of user ids and alias ids and also adds in all existing user ids. When you join, you'll get the original records. You could also do this with two separate queries connected by a join.