mySQl,Query:如何从数据库中自定义选择?

时间:2016-05-14 11:03:16

标签: php mysql sql

我有四张桌子:

courses, allocate_rooms, rooms, departments 

查询:

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

从查询中我必须将选择视图设为rooms.room_number,allocate_rooms.start-allocate.rooms_end;如果没有与该课程相关的数据,我必须显示" 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"

如何重写上述查询?如果有人帮我找到解决方案。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用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

答案 1 :(得分:0)

我不确定这是否是你需要的,但试试这个:

您可以使用DECODE获取所需内容。

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;

答案 2 :(得分:0)

以下是解决方案:

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