0

I hope my title makes sense but basically what I need to do is select some rows from a mysql table but I want one particular row to always be listed first. Normally I would use "order by field" for this but this particular row has to match a value in another table.

SCHEDULES TABLE
----------
ID
NAME
COMPANYID
DESCRIPTION


COMPANIES TABLE
----------
ID
NAME
ACTIVESCHEDULEID

So I want to select all the schedules from schedules table where companyid = 1, but the schedule that is the active schedule for this company needs to be listed first, and that bit of information is stored in the companies table.

I was hoping I could do something like this:

select s.id
from schedules s, companies c
where s.companyid = c.id 
and s.companyid = 1 
order by field(s.id,s.id = c.activescheduleid)

But that's not working for me. Any ideas?

4

2 回答 2

0
select s.id
from schedules s, companies c
where s.companyid = c.id 
and s.companyid = 1 
order by
  s.id,
  s.id = c.activescheduleid

您可能希望使用ASCorDESC作为二阶条件,具体取决于首先或最后排序的身份。

于 2013-07-13T19:10:33.303 回答
0

order by子句中可以有多个条件。第一个可以与活动的 scheduleid 匹配:

select s.id
from schedules s join
     companies c
     on s.companyid = c.id 
where s.companyid = 1 
order by (s.id = c.activescheduleid) desc, s.id

desc是因为 MySQL 中的“真”值被视为 a1而“假”被视为0. 因此,这将返回1活动计划 ID。要使其首先出现,请使用desc.

于 2013-07-13T19:11:11.277 回答