1

I'm pretty bad when it comes to designing database queries, can I have some help?

Here are the 2 tables (samples):

TABLE user: id, name, relationship_type_id
TABLE relationship_type: relationship_type_id (fk), relationship, contributing

Now, I want to use a single query to get:

  1. All the relationship_type table's records (i.e. SELECT * FROM relationship_type)
  2. And the specific relationship of the user who has id = 5

So the result is something like this (assuming table relationship_type has only 2 records)

"data": [
        {
            "relationship": "Friend" // for user id = 5
        },
        {
            "relationship_type_id": "1"
            "relationship": "Partner"
        },
        {
            "relationship_type_id": "2"
            "relationship": "Friend"
        }
    ],
1
  • SELECT columns FROM table1 JOIN table2 ON columnA = columnB [WHERE other conditions] Commented May 12, 2015 at 7:29

2 Answers 2

1
SELECT user.id, user.name
FROM user
LEFT JOIN relationship_type
ON user.relationship_type_id=relationship_type.relationship_type_id WHERE user.id=5;
Sign up to request clarification or add additional context in comments.

4 Comments

Oops, it lists everything.
off course it is simple query to fetch record from two tables put you conditions and customize it. just use user.relationship_type_id=relationship_type.relationship_type_id where and put condition the data will be filter.
Is there anyway I could list everything in table relationship_type as well?
relationship_type.relationship add column after column user.name with comma separated you will get you desired column
0
SELECT 
     rt.*, u.*
FROM 
     relationship_type rt
  LEFT JOIN 
     user u
    ON rt.relationship_type_id = u.relationship_type_id
WHERE 
     u.id = 5
UNION
SELECT *
FROM relationship_type;

1 Comment

It's close. Is there anything I could list everything within table relationship_type as well?

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.