So basically I have 3 differnet tables named member, phone_message and pc_message each with the following columns:
member = (id, cell_num)
phone_message = (phone_num, content, received_at)
pc_message = (member_id, content, sent_at)
What i'm trying to do here is to list all the messages including both phone and pc that are received or sent for each member. To do that i need to combine those tables into one using SQL queries like JOIN and UNION. Any help?
CodePudding user response:
You can try below query, I have used inner join so that messages only sent by matching members will be diplayed. In addition to that, I have added one extra column as device which will identify whether the message is sent on phone or pc.
select m.id as memberId, m.cell_num as phoneNumber, p.content as Message, p.received_at as recieveDate,'Phone' as device from member m
inner join phone_message p on m.cell_num = p.phone_num
union
select m.id as memberId, m.cell_num as phoneNumber, pc.content as Message, pc.sent_at as recieveDate,'PC' as device from member m
inner join pc_message pc on m.id = pc.member_id
CodePudding user response:
Try this;
select m.id as memberId, m.cell_num as phoneNumber, p.content, p.received_at as recieveDate from member m
inner join phone_message p on m.cell_num = p.phone_num
union
select m.id as memberId, m.cell_num as phoneNumber, pc.content, pc.sent_at as recieveDate from member m
inner join pc_message pc on m.id = pc.member_id