简体   繁体   中英

SQL nested select fixed

I have two tables, hours and days, hours store the hours a profesional has available in a day. Days, store the the reserved hours,

table_hours

id  | begin   | end    | profesional 
1   | 09:00   |  10:00 | 1 
2   | 10:00   |  11:00 | 1 
3   | 11:00   |  12:00 | 1 
4   | 13:00   |  14:00 | 1 
5   | 14:00   |  15:00 | 1 
6   | 09:30   |  10:30 | 2 
7   | 13:00   |  14:30 | 2 
8   | 14:30   |  15:30 | 2 

table_days

id  | hour_id | day
1  | 1        |20151201 
2  | 3        |20151201 
3  | 6        |20151201 
4  | 2        |20151205 
5  | 7        |20151205 
6  | 8        |20151205

I, tried the following query, but do not worked.

SELECT *, (SELECT day from days where hours.id = days.hours_id and day = '20151201') as 'day' 
FROM hours 
where profesional = 1 

As result I would like to have all results from profesional and a date just when match as bellow

table_result

id  | begin | end    | profesional | day
1   | 09:00 |  10:00 | 1           |20151201
2   | 10:00 |  11:00 | 1           |NULL
3   | 11:00 |  12:00 | 1           |20151201
4   | 13:00 |  14:00 | 1           |NULL
5   | 14:00 |  15:00 | 1           |NULL

Use LEFT JOIN to get all the rows in the first table, and return NULL in the columns from the second table when there's no matching row.

SELECT h.*, d.day
FROM hours AS h
LEFT JOIN days AS d ON h.id = d.hours_id AND d.day = '20151201'
WHERE h.profesional = 1
SELECT table_hours.id, table_hours.begin, table_hours.end, table_hours.professional, table_day.day  
FROM table_day LEFT JOIN table_hours ON  table_day.id=table_hours.id AND table_day.day= '20151201'
Where day= professional=1

I think, you have already got the solution here from other answers. But I just wanted to point out another thing, you have set your database in a wrong way. Instead of keeping hour_id in days table, keep day_id in hours table. It should reduce rows in your database and help you save storage in the long run. So it can be like this:

table_hours

id  | day_id  | begin   | end    | profesional 
1   | 1       | 09:00   |  10:00 | 1 
2   | 2       | 10:00   |  11:00 | 1 
3   | 1       | 11:00   |  12:00 | 1 
4   | 3       | 13:00   |  14:00 | 1 
5   | 3       | 14:00   |  15:00 | 1 
6   | 1       | 09:30   |  10:30 | 2 
7   | 2       | 13:00   |  14:30 | 2 
8   | 2       | 14:30   |  15:30 | 2 

table_days

id  | day
1   | 20151201 
2   | 20151205 

And now change your SQL like this

SELECT h.*, d.day
FROM hours AS h
LEFT JOIN days AS d ON h.day_id = d.id AND d.day = '20151201'
WHERE h.profesional = 1

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