0

I have a simple mysql database where user has its own events table and invited events table.

User-->>Own events (user_id is foreign key )
User and Own events-->>Invited Events(user_id is foreign key, event id is foreign key)

I want to get OWN EVENT details from Invited Events where user_id is equal to some number

Example:

enter image description here

I try:

$user_id = $_POST["user_id"];
$stmt = $mysqli->query("SELECT A1.event_id,A1.root_folder,A1.event_name,A1.date,A1.location,A2.user_id FROM OWN_EVENTS A1, INVITED_EVENTS A2 WHERE A2.user_id=$user_id");

$rows = array();
while($r = mysqli_fetch_assoc($stmt)) {
    $rows[]=$r;
}

This supposed give me (one row) event details of event_id=3 where user_id=58 but this returns all the rows in the OWN_EVENTS table.

What am I doing wrong ?

1 Answer 1

3

Currently, you query returns cartesian product.

You need to tell the optimizer how the two tables are connected with each other.

SELECT  A1.event_id,A1.root_folder,A1.event_name,A1.date,A1.location,A2.user_id 
FROM    OWN_EVENTS A1 
        INNER JOIN INVITED_EVENTS A2 
           ON A1.columnName = A2.columnsName  // columns that defines their relationship
WHERE   A2.user_id=$user_id

To further gain more knowledge about joins, kindly visit the link below:

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for quick answer that works fine, I guess I need to learn more about joins in sql.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.