Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

mysql - Minimizing SQL queries using join with one-to-many relationship

So let me preface this by saying that I'm not an SQL wizard by any means. What I want to do is simple as a concept, but has presented me with a small challenge when trying to minimize the amount of database queries I'm performing.

Let's say I have a table of departments. Within each department is a list of employees.

What is the most efficient way of listing all the departments and which employees are in each department.

So for example if I have a department table with:

id   name
1    sales
2    marketing

And a people table with:

id   department_id   name
1    1               Tom
2    1               Bill
3    2               Jessica
4    1               Rachel
5    2               John

What is the best way list all departments and all employees for each department like so:

Sales

  • Tom
  • Bill
  • Rachel

Marketing

  • Jessica
  • John

Pretend both tables are actually massive. (I want to avoid getting a list of departments, and then looping through the result and doing an individual query for each department). Think similarly of selecting the statuses/comments in a Facebook-like system, when statuses and comments are stored in separate tables.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get it all in a single query with a simple join, e.g.:

SELECT   d.name AS 'department', p.name AS 'name'
FROM     department d
  LEFT JOIN people p ON p.department_id = d.id
ORDER BY department

This returns all the data, but it's a bit of a pain to consume, since you'll have to iterate through every person anyway. You can go further and group them together:

SELECT   d.name AS 'department',
         GROUP_CONCAT(p.name SEPARATOR ', ') AS 'name'
FROM     department d
  LEFT JOIN people p ON p.department_id = d.id
GROUP BY department

You'll get something like this as the output:

department | name
-----------|----------------
sales      | Tom, Bill, Rachel
marketing  | Jessica, John

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...