2012-09-18 164 views
-1

tbl_usersSQL條件顯示記錄

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 

我嘗試此查詢或者顯示用戶和EMP名

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記錄然後全部休息?

+0

你就不能'ORDER BY pay_status DESC'? – hims056

+0

我試過了,但我們如何給下一個條件? 未付 e_id = 0 – Anu

+0

下一個條件?哪一個? – hims056

回答

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; 
+0

我們如何避免「where」條件.... 因爲它只顯示e_id = 0 輸出就像 1)所有記錄**未付** 2)當所有未付費記錄結束時顯示** e_id = 0 * * 3)當所有的e_id = 0記錄顯示**休息**全部 – Anu

+0

@Anu請參閱最新的答案。 – hims056

+0

@Anu由於你沒有回覆,我們無法幫助你。 – hims056

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 
+0

它沒有運行! – Anu

+0

有什麼錯誤?如果是的話是什麼? –

+0

沒有錯誤.. 未示出的值也,即使不爲空 – Anu