-1

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

我试过这个查询来显示用户和员工姓名

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

我们如何给条件(order by 或其他 1)先显示未付(pay_status)记录然后e_id=0记录然后全部休息?

4

2 回答 2

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
于 2012-09-18T06:06:13.860 回答
0

您的 fromWHERE子句查询应该是这样的:

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;

编辑:(来自OP的评论

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

ORDER BY pay_status DESC, e_id ASC;
于 2012-09-18T06:51:53.380 回答