sql条件显示记录

时间:2012-09-18 05:44:09

标签: php mysql sql database codeigniter

tbl_users

u_id | u_type | u_first_name
 1      U        I_am_user
 2      E        I_am_emp   
 3      E        I_am_emp2

tbl_order

o_id | u_id | e_id | o_status | pay_status
  1     1       0    pending    Unpaid
  2     1       2    pick       Paid
  3     1       0    pending    Unpaid
  4     1       3    Pick       paid

我尝试过此查询以显示用户和\ temp名称

SELECT o.*, a.u_first_name as user, b.u_first_name as emp
  FROM `tbl_order` AS o
       LEFT JOIN tbl_users AS a ON a.u_id = o.u_id 
       LEFT JOIN tbl_users AS b ON b.u_id = o.e_id

o_id | u_id | e_id |  user |  emp | pay_staus

我们如何给出条件(按顺序或其他1)首先显示未付费(pay_status)记录 然后e_id=0记录然后全部休息?

2 个答案:

答案 0 :(得分:0)

试试这个:

select * from(
SELECT o.*, a.u_first_name as user, b.u_first_name as emp, 0 as rnk 
FROM `tbl_order` AS o
LEFT JOIN tbl_users AS a ON a.u_id = o.u_id 
LEFT JOIN tbl_users AS b ON b.u_id = o.e_id
where pay_status='Unpaid'    
union all
SELECT o.*, a.u_first_name as user, b.u_first_name as emp, 1 as rnk 
FROM `tbl_order` AS o
LEFT JOIN tbl_users AS a ON a.u_id = o.u_id 
LEFT JOIN tbl_users AS b ON b.u_id = o.e_id
where pay_status!='Unpaid' and    e_id=0
union all
SELECT o.*, a.u_first_name as user, b.u_first_name as emp, 2 as rnk 
FROM `tbl_order` AS o
LEFT JOIN tbl_users AS a ON a.u_id = o.u_id 
LEFT JOIN tbl_users AS b ON b.u_id = o.e_id
where pay_status!='Unpaid' and    e_id!=0)a
order by rnk

答案 1 :(得分:0)

WHERE子句中的查询应如下所示:

WHERE e_id = 0 OR pay_status = 'Unpaid'
ORDER BY pay_status DESC;

所以你的整个查询应该是这样的:

SELECT o.*, a.u_first_name as user, b.u_first_name as emp
  FROM `tbl_order` AS o
       LEFT JOIN tbl_users AS a ON a.u_id = o.u_id 
       LEFT JOIN tbl_users AS b ON b.u_id = o.e_id
  WHERE e_id = 0 OR pay_status = 'Unpaid'
  ORDER BY pay_status DESC;

编辑:From OP's comment

如果您想按特定顺序显示所有记录,您只需要使用ORDER BY这样的句子:

ORDER BY pay_status DESC, e_id ASC;