Search code examples
sqlselectphpmyadmininner-join

Sql query select all messages from everybody inside every group where this one user is at


I'm trying to get all of the messages, from EVERY user, from 2 groups, where the user is located. But I don't know how to get all message from every group. This is my code so far:

SELECT DISTINCT m.*
FROM `message` m 
INNER JOIN users u
ON u.id = m.idUser
LEFT JOIN whats_app w
ON w.idUser= u.id 
WHERE u.id = w.idUser

So there is ONLY ONE user in 2 groups. I wan't to get all messages from everybody inside the groups where the ONE user is located at.

this is some simple sql query als example:

    create table users (
id                  int         PRIMARY KEY         NOT NULL,
name                varchar(60)
);

create table whatsapp(
idUser              ,
idGroup             int
);

create table allGroups(
id                  int         PRIMARY KEY         NOT NULL,
name                varchar(60)
);

create table message_send(
id                  int,
idUser              int,
message             text
);

INSERT INTO users(id, name) VALUES
(1, 'John'),
(2, 'Martijn'),
(3, 'Rick'),
(4, 'Vera'),
(5, 'Leon');

INSERT INTO allGroups(id, name) VALUES
(1, 'School'),
(2, 'Friends'),
(3, 'moreFriends'),
(4, 'secretmeeting');

INSERT INTO message_send(id, idUser, message) VALUES
(1, 2, 'How are you feeling today?'),
(2, 1, 'What up?'),
(3, 4, 'I am fine, you?'),
(4, 1, 'hi!');

Solution

  • create table message_send(
    id                  int,
    idUser              int,
    idGroup             int,
    message             text
    );
    

    Create message table like this and then just directly join with user and group you will get the output there is not need for the table watsapp

    select  b.name,message 
    from 
    message_send as a,
    users as b
    where
    a.idUser=b.id
    

    Similarly join the group table