简体   繁体   中英

How to select ALL results from a SQL query and eliminate the null values

Imagine I have four tables:

Agents

| agent_id | agent_name |

Teams

| team_id | team_name |agent_id |

Menu

| menu_id | menu_name |

Team_assignment

| menu_id | team_id|

I need to write a query that selects all agents that are assigned to all teams and all queues and disregard the ones that are not assigned to a queue. Note that every agent is always assigned to a team but it's not necessary that the agent is assigned to a queue.

Since you stated that this is for a school project, I'll try to stay within the guidelines mentioned here: How do I ask and answer homework questions?

From what I can make up from your question you basically want to select all the data from the different table s join ing them on one of the columns in the first table a equals = a column from the second table b . Most commonly where the primary key from one table equals the foreign key from another table. Then you want to add conditions to your query where for example some column from table 1 equals = some value.

Do you catch my drift? 😏
No?

You want to SELECT a.*, b.* everything FROM table Agents a JOIN ing table Teams b ON column a.agent_id being equal to = column b.agent_id

You probably want to JOIN another table, lets say Team_assignment c ON column c.team_id being equal to = b.team_id .

You can JOIN more tables in the same way.

Sadly, I do not understand what you mean by the ones that are not assigned to a queue but it sounds like a condition that your query needs to match, so WHERE the potential column a.is_assigned_to_queue equals = true AND for example a.agent_name IS NOT NULL

If you got this far you should have been able to catch onto my drift 😎, congrats. This way hopefully you also got a better understanding of how building query works, instead of me just blatantly giving you the answer and you learn nothing from it. Like this:

SELECT a.*, b.*, c.*, d.* FROM Agents a
JOIN Teams b ON a.agent_id = b.agent_id
JOIN Team_assignment c ON c.team_id = b.team_id
JOIN Menu d ON d.menu_id = c.menu_id
WHERE a.is_assigned_to_queue = true
  AND a.agent_name IS NOT NULL;

Now it is possible copy and pasting the snippet above will not work, that is because I'm not an SQL expert and I had to refresh my old memories about SQL myself by googling it. But that's the nice part of actually learning it. Being able to explain it to someone else :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM