Fetch multiple records from multiple database using single query - mysql

I have two tables as follows:-
Users (Table1)
id name email passs
1 u1 uemail1 pass1
2 u2 uemail2 pass2
3 u3 uemail3 pass3
4 u4 uemail4 pass4
Messages (Table2)
mess_id sender receiver message_text send_time
1 1 2 text1 2019-03-25 09:39:05
2 1 2 text2 2019-03-30 15:10:54
3 1 3 text3 2019-03-30 15:11:59
4 1 4 text4 2019-03-30 15:12:48
5 1 4 text5 2019-03-30 15:13:53
6 4 1 text6 2019-04-09 09:26:53
The logged in user is u1 and i want to get the latest conversation which is the 6th one okay.
Now what i want is to find the latest conversation of u1 and with whom and then find the details from users table of other user with whom u1 had the latest conversation
I hope you got my question and it's clear to everyone.
How can i do all this is 1 query
The result will be the other user's detail like this in the above case the user will be u4
id name email passs
4 u4 uemail4 pass4
So far i have tried this but not getting the result what i wanted
select name from users where id=(select receiver_id,sender_id from messages where receiver_id or sender_id=1 order by send_time desc limit 1)

One way is to determine the other user id in a Derived Table, and then join this to the user table, to get the user details.
SELECT
u.*
FROM
user AS u
JOIN
(
SELECT
IF(sender <> 1, sender, receiver) AS other_user /*Logged-in User Id is mentioned here */
FROM messages
WHERE sender = 1 OR receiver = 1 /*Logged-in User Id is mentioned here */
ORDER BY send_time DESC LIMIT 1 /*Get the latest message row */
) AS dt ON dt.other_user = u.id
IF(sender <> 1, sender, receiver) determines the other user id. If sender is not 1 (logged-in user), then we consider sender as the other user, else receiver. This is based on a (mostly valid) assumption that the sender and receiver will always be different values.

Here's a somewhat complex but very general way of solving the problem. It finds the maximum send/receive time for each user in a derived table, then JOINs that to the messages table to find the other user related to that message, and then JOINs that again to the users table to find that user's details. The user of interest is specified in the WHERE clause at the end of the query.
SELECT u2.*
FROM users u1
JOIN (SELECT user, MAX(send_time) AS send_time
FROM (SELECT sender AS user, MAX(send_time) AS send_time
FROM messages
GROUP BY sender
UNION
SELECT receiver, MAX(send_time)
FROM messages
GROUP BY receiver) mt
GROUP BY user) mt ON mt.user = u1.id
LEFT JOIN messages m1 ON m1.sender = mt.user AND m1.send_time = mt.send_time
LEFT JOIN messages m2 ON m2.receiver = mt.user AND m2.send_time = mt.send_time
JOIN users u2 ON u2.id = COALESCE(m1.receiver, m2.sender)
WHERE u1.id = 1
Output:
id name email passs
4 u4 uemail4 pass4
Demo on dbfiddle

Related

join to fetch users who do not have a busy date--the available users

I am trying to join two tables User and Busy Days. I want to fetch all the users who do not have a busy date--the available users.
User
user_id
username
1
John
2
Doe
Busy Days
id
busy_date
user_id
1
2022-05-26
1
2
2022-05-26
2
3
2022-05-29
1
4
2022-06-01
2
I want to search by date. If 2022-05-26 the result should be zero because both users have a busy day on that date, but if 2022-05-27 both users should appear.
select username from user
where id not in (select user_id from busy_days where busy_date = "2022-05-26")
Works for me with not exists.
select U.USER_ID
from USER U
where not exists (select 1
from BUSY_DAYS B
where B.USER_ID = U.USER_ID
and B.BUSY_DATE = 'some date')
Note: Replace some date with your actual date, e.g. 2022-05-26.
Refer to this db<>fiddle
For joining two tables
SELECT * FROM User INNER JOIN Busy_Days ON User.user_id=Busy_Days.user_id;
Then to achieve the result
SELECT * FROM User INNER JOIN Busy_Days ON User.user_id=Busy_Days.user_id WHERE NOT Busy_date=2022-05-27;
SELECT * FROM User INNER JOIN Busy_Days ON User.user_id=Busy_Days.user_id WHERE NOT Busy_date=2022-05-26;
Hope this helps you if you have any query regarding this please feel
free comment

same table select friend request

I am writing a chat database.
If users are friends, then they have each other in the friends table, like user 1 and 2 or 1 and 5 in my table(see link).
But I want to find out who sent the application as a friend. In this case, only one person stores the id of another person, like user 1 who sent request for user 7.
I have table:
(only 3 column: idfriend, iduser, friend_id)
How i can select user id (friend_id) who sent request for friend?
If i chose user 1, then my sql must return this friend request:
|friend_id|
7
i try this:
select friend.friend_id from friend inner join friend as friends on
friend.iduser != friends.friend_id and friends.iduser != friend.friend_id
and friend.iduser != friends.iduser and friend.friend_id !=
friends.friend_id where friend.iduser = 1
but this select 7,2 and 5. Need only 7
With NOT EXISTS:
select t.friend_id from friend t
where t.iduser = 1
and not exists (
select 0 from friend
where iduser = t.friend_id and friend_id = t.iduser
)
See the demo.
Results:
| friend_id |
| --------- |
| 7 |
Hopefully this is the solution you are looking for:
select t1.iduser, t1.friend_id
from friends t1
where t1.friend_id not in
(
select t2.iduser
from friends t2
where t2.friend_id = t1.iduser
)

fetch results using join Mysql

MY USERID IS 1
TABLE users
USERID NAMES EMAIL
1 KAT 1#1.com
2 JOHN 2#2.com
3 FIK 3#3.com
TABLE comunity
COMUNITY_ID USERID MYFANS
1 1#FROM TABLE USERS 1#1.com
2 2#FROM TABLE USERS 1#2.com
3 3#FROM TABLE USERS 1#3.com
SELECT u.USERID, u.NAME FROM
users u
INNER JOIN comunity c ON u.USERID = c.USERID
WHERE c. MYFANS = '1#1.com'
with his example i only get users which have my email in column MYFANS. but i want to get also users which i have their emails in MYFANS Column
its like select myfans where my email is '1#1.com' and these emails which i have in myfans where my userid = '1'

How to get different results from one mysql table?

I have a user table in the database where all users of the system are stored.
The table has a user_id and a business_name and a first_name.
Some users are merchants and get a business name,
some users are consumers and get a first name.
In a second table I have transactions with a user_id and a merchant_id (which are defining the transaction) and an amount. Both ids reference to user table.
Table users:
user_id bus_name first_name role_id
1 Thomas 10
2 comp1 7
3 Peter 10
4 comp2 7
(role_id is defining with 10=consumer, 7=merchant)
Table transactions:
trans_id amount user_id merchant_id
1 12 1 2
2 23 3 2
3 34 3 4
4 19 1 4
Now I want to have a query with a result as one table:
This table should contain the transaction with amount, user_id, first_name, merchant_id and bus_name.
I want to get this result:
trans_id amount user_id first_name merchant_id bus_name
1 12 1 Thomas 2 comp1
2 23 3 Peter 2 comp1
3 34 3 Peter 4 comp2
4 19 1 Thomas 4 comp2
I have the problem that either I get only the first_name and empty bus_name or I get only the bus_name but empty first_name.
I am using a left join:
...
left join `users`
on(
(`transactions`.`user_id` = `users`.`user_id`)
)
...
But for this I would get for user_id=1 the first_name=Thomas and the bus_name='' would be empty because I only reference to one line in table and not also to different user with user_id=2.
But I want to say something like:
for trans_id=1
get first_name FROM users WHERE transactions.user_id = users.user_id
AND
get bus_name FROM users WHERE transactions.merchant_id = users.user_id
Thanks for your help, I tried so many things but it does not work.
You have to join the user table twice:
SELECT t.*, u.first_name, m.bus_name
FROM transactions t
JOIN users as u
ON t.user_id = u.user_id
JOIN users as m
ON t.merchant_id = m.merchant_id
you could use a duoble join in users table
select a.trans_id, a.amount , a.user_id, b.first_name, a.merchant_id, c. bus_name
from transactions a
inner join users b on a.user_id = b.user_id and b.role_id = 10
inner join users c on a.merchant_id = c.user_id and c.role_id = 7
To join the user table twice worked fine. With "left join users as consumer" I create a kind of a virtual users table called "consumer", this one is joined. Of course in select I had to adjust table name as well. Same for second "virtual" table od users, called "merchant".
select
`transactions`.`trans_id` AS `trans_id`,
`transactions`.`merchant_id` AS `merchant_id`,
`merchant`.`bus_name` AS `bus_name`,
`transactions`.`user_id` AS `user_id`,
`consumer`.`first_name` AS `first_name`,
`cards`.`card_id` AS `card_id`,
`cards`.`serial_no` AS `serial_no`
from (
`transactions`
left join `cards`
on(
(`cards`.`card_id` = `transactions`.`card_id`)
)
left join `users` as consumer
on(
(`consumer`.`user_id` = `transactions`.`user_id`)
)
left join `users` as merchant
on(
(`merchant`.`user_id` = `transactions`.`merchant_id`)
)
)

Cakephp reciprocal friendship system

I've been trying to figure out for a week or so, how I can make a proper friendship system in CakePHP. I've read this and this thread but I can't get it to work.
I've read a lot more threads regarding this, but nobody seems to have a proper example.
I currently have a table users (id, username, password, e-mail etc.) and a table friendships (id, user_to, user_from, status).
Step 1 - Friendship request
If a user does a friendship request, then a row is inserted with the requesting user_id and the user_id of the user from whom the friendship is request, so it could look like:
id | user_from | user_to| status
1 | 1 | 2 | 0
This way I can easily show pending friends of user_id = 2, by selecting all records where user_to = 2
Step 2 - Confirm friendship
I've set it up so that user_id 2 now sees that user_id 1 wants to become friends, if he clicks the confirmation link, the status will be changed to 1, see below
id | user_from | user_to| status
1 | 1 | 2 | 1
I created all kinds of checks so the row stays unique.
Step 3 - Show friends
I thought this would be easy, if I want to show the friends of user_id = 1 then I just do a select with user_from = 1 OR user_to = 1, however this doesn't work.
User_id 1 can be a requester but can also be requested, so a JOIN will show strange results.
Does anyone know a solution? I'm happy to rebuild the entire system if I'm not doing the entire thing right! Any hints in the right direction are welcome as well...
Here is my solution : the difficulty lies in the correct request because friend requests can be crossed (if A asks B or B asks A will be stored the opposite way in the "to" and "from" fields of the table). Lets do it like that and user UNION and aliases to get friends from any user independently of the relation table bellow.
The [friends] table (relation): to|from|statut(pending,confirmed)
"to" and "from" > foreign_keys constraint to a [users] table
The request below always gives the wanted results ! (replace %d by the user ID or user Id in the SESSION
SELECT
users.userNickname,
friends.to AS friendUser,
friends.from AS currentUser,
friends.statut
FROM
users
INNER JOIN
friends
ON
users.userId = friends.to
WHERE
friends.from = '%d'
UNION
SELECT
users.userNickname,
friends.from AS friendUser,
friends.to AS currentUser,
friends.statut
FROM
users
INNER JOIN
friends
ON
users.userId = friends.from
WHERE
friends.to = '%d'
You can find friend requests to ID = 1 this way:
select * from Users u1 where u1.user_to = 1 and u1.user_from not in (select u2.user_to
from Users u2 where u2.user_from = u1.user_to)
You can find friend requests from ID = 1 this way:
select * from Users u1 where u1.user_from = 1 and u1.user_to not in (select u2.user_from
from Users u2 where u2.user_to = u1.user_from)
You can find mutual friendships of ID = 1 this way:
select * from Users u1 where ((u1.from = 1) or (u1.to = 1)) and 0 < (select count(*) from
Users u2 where u1.from = u2.to and u1.to = u2.from)
This code was not tested, but you get the idea.