Finding Values of same ID from different table - mysql

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);

Related

SQL query to find largest id for each user_id

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

Distinct select statement using two tables

I've looked around the forum for a while now, but I can't find a solution for the following.
I've got two tables, users and bookings.
users:
unique id, firstname and lastname
bookings:
uniquide id, userId, arrival and departure
For every booking a user makes, the bookings table will contain the unique users id in the field userId.
I now want to get the firstname and lastname from table users, and all bookings which are made depending on the userId.
select users.*, bookings.* FROM users, bookings WHERE bookings.userId =:id GROUP BY bookings.id
The statement above returns all bookings according to the userId, but it also contains the user itself multiple times, i just need the user data once.
select u.id, u.firstname, u.lastname, b.id as bookingid, b.arrival, b.departure from users u JOIN bookings b ON u.id = b.userid
doing GROUP BY on booking.id makes no sense in this case, as booking.id is the lowest level element. Now, you could group by users.id, but then you can no longer return all the individual bookings - but you can return a lot of helpful things like COUNT(bookings.id) AS NbrBookings or MIN(arrival) or MAX(departure)
but you can't have aggregate data and inidividual data at the same time.
users.*, bookings.*
instead of this specify the relevant column names

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.

Single MySQL query which checks another table for rows

I have a Users table and a Payments table. I need a query which lists the users who DO NOT have a record in the payments table where the field PaymentCompleted=1.
These are the columns in the tables (simplified):
Users: UserID, UserName
Payments: PaymentID, UserID, PaymentCompleted
The query should select the field UserName.
select distinct UserName
from Users left outer join Payments on Users.UserID = Payments.UserID
where PaymentCompleted is NULL or PaymentCompleted != 1
SELECT UserName
FROM Users u
WHERE NOT EXISTS(Select 1
from Payments p
Where p.UserId = u.UserId
AND p.PaymentCompleted = 1)
select * from t_users T where T.userid not exists (select p.userid from t_payments t where PaymentCompleted=1).
One note: "not in" clauses can be computationally inefficient for large numbers of records. If you start seeing performance issues, you may want to do some refactoring/redesign.