简体   繁体   中英

Learning SQL: Query for rows in diff tables based on if a column value is set

I am doing a side project to help me learn SQL.

I have setup 2 different tables:

computers
+------------------+-----------+------+-----+---------+-------+
│| Field            | Type      | Null | Key | Default | Extra |
│+------------------+-----------+------+-----+---------+-------+
│| serial_number    | char(25)  | NO   | PRI | NULL    |       |
│| operating_system | char(10)  | YES  |     | NULL    |       |
│| purchase_year    | int(4)    | YES  |     | NULL    |       |
│| assigned_to      | char(100) | YES  |     | NULL    |       |
│+------------------+-----------+------+-----+---------+-------+

employees
│+------------+-----------+------+-----+---------+-------+
│| Field      | Type      | Null | Key | Default | Extra |
│+------------+-----------+------+-----+---------+-------+
│| email      | char(100) | NO   | PRI | NULL    |       |
│| first_name | char(25)  | NO   |     | NULL    |       |
│| last_name  | char(25)  | NO   |     | NULL    |       |
│| office     | char(5)   | NO   |     | NULL    |       |
│| assigned   | char(25)  | YES  |     | NULL    |       |
│+------------+-----------+------+-----+---------+-------+

These both have a few entries while I am testing, but in trying to write a search function based off the employee email, I am reaching a snag with SQL queries. I'm pouring through the documentation, but not understanding it well, and can't find a good example of what I am trying to do to follow along with.

Here is what I am attempting to do with the query: I want to grab a the employee row matching email address provided, and if the "employees.assigned" field is set (not null, think EXIST is used?) then I want to also grab the "computers.serial_number" row matching that column value

I can do what I want with 2 separate queries, but I want to see if it is possible with only one to clean up code and make the query as fast as possible. Any further documentation you think is worthwhile for this project is very welcome as well!

For those people finding this on google:

What I found worked for my need:

SELECT * FROM employees LEFT JOIN computers ON employees.assigned=computers.serial_number WHERE email='email@example.com';

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