0

I have researched about this for days now and I can't seem to find the right query for me.

Tables

1. Projects

  • id
  • projectname
  • date

2. Notes

  • noteid
  • note
  • projectid

Wanted Result:

array =>
    project1 =>
        Notes1
        Notes2
        Notes3

    project2 =>
        Notes1
        Notes2
    project3 =>
    ….........

I am struggling to create a single query that will populate the result i wanted - Select all fields from projects and create another array for each id to hold all results that match project.id on notes.projectid.

1 Answer 1

2

You will need to use what ever language your using to organize the array for you.

The SQL query you want to use is:

SELECT projects.*, notes.noteid, notes.note
FROM projects LEFT JOIN notes ON
    projects.id = notes.projectid
LIMIT 250;

Use a limit so you don't end up with a huge dataset. You can set the limit to whatever suits your needs or omit it if you are sure you don't need to wory about dataset size.

This will return a dataset like this:

+----------+-------------+----------+----------+----------+
| id       | projectname | date     | noteid   | note     |
+----------+-------------+----------+----------+----------+
| 1        | Project1    | 1/1/2000 | 1        | Notes1   |
| 1        | Project1    | 1/2/2000 | 2        | Notes2   |
| 1        | Project1    | 1/3/2000 | 3        | Notes3   |
| 2        | Project2    | 1/4/2000 | 4        | Notes1   |
| 2        | Project2    | 1/5/2000 | 5        | Notes2   |
| 3        | Project3    | 1/6/2000 | NULL     | NULL     |
+----------+-------------+----------+----------+----------+

I used a LEFT JOIN for the instances that a project doesn't have any notes yet. You can see what the results would look like for Project3. Then its up to your programming language to organize your dataset. Without knowing the limitations for your language, I don't want to theorize too much about how to organize this.

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

Comments

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.