简体   繁体   中英

mySQl, Query: How to customize selection from database?

I have four tables:

courses, allocate_rooms, rooms, departments 

Query:

SELECT
    courses.`name`,
    courses.`code`,
    allocate_rooms.`start`,
    allocate_rooms.`end`,
    rooms.room_number
FROM
    departments
JOIN courses ON departments.id = courses.department_id
LEFT JOIN allocate_rooms ON allocate_rooms.course_id = courses.id
LEFT JOIN rooms ON allocate_rooms.room_id = rooms.id
WHERE
    departments.id = 1

From the Query I have to make a selection view as rooms.room_number, allocate_rooms.start-allocate.rooms_end; and if there is no data related to that course I have to show "Not Scheduled Yet".

Eg: R.No: 301,12:00-12:30; (if the course related data is there otherwise it will show "Not Scheduled Yet"

How do I rewrite the above Query? If anybody help me to find the solution.

You can try with ifnull

SELECT courses.name, courses.code, allocate_rooms.start,
  allocate_rooms.end   , 
   case rooms.room_number 
         WHEN IS NULL THEN 'No Rooms allocated'
         WHEN 0 THEN 'No Rooms allocated'
         ELSE room.room_number
         end
FROM departments 
join courses on departments.id = courses.department_id 
left join allocate_rooms on allocate_rooms.course_id=courses.id 
left join rooms on allocate_rooms.room_id=rooms.id 
WHERE departments.id=1

I'm not sure if it's what you need, but try this:

You can use DECODE for getting what you need.

SELECT
    c.name name
   ,c.code code
   ,decode(ar.start,NULL,'Not Schedule Yet') START
   ,decode(ar.end,NULL,'Not Schedule Yet') END
   ,r.room_number roomnum
FROM
    departments d
   ,courses c
   ,allocate_rooms ar
   ,rooms r
WHEREd.id = c.id
AND ar.course_id = c.id
AND ar.room_id = r.room_id
AND d.id = 1;

Here is the solution:

SELECT courses.name, courses.code,COALESCE( CONCAT('R. No',':',rooms.room_number,', ',days.name ,', ', allocate_rooms.start,' - ',allocate_rooms.end),"Not Assigned Yet") AS Schedule 
FROM departments join courses on departments.id = courses.department_id
left join allocate_rooms on allocate_rooms.course_id=courses.id 
left join rooms on allocate_rooms.room_id=rooms.id
left join days on allocate_rooms.day_id=days.id WHERE departments.id=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