2012-02-06 135 views
0

我想從第基於一個特定的列值,增加一些動態內容。 有可能嗎? 例如,動態查詢字符串

SELECT BILL.BILL_NO AS BILLNO, 
     IF(BILL.PATIENT_ID IS NULL,"CUS.CUSTOMERNAME AS NAME","PAT.PATIENTNAME AS NAME") 
FROM 
     BILL_PATIENT_BILL AS BILL 
     LEFT JOIN IF(BILL.PATIENT_ID IS NULL," RT_TICKET_CUSTOMER AS CUS ON BILL.CUSTOMER_ID=CUS.ID"," RT_TICKET_PATIENT AS PAT ON BILL.PATIENT_ID=PAT.ID") 

但此查詢不起作用。

這裏

BILL_PATIENT_BILL表是一種常見的表。
它可以有PATIENT_IDCUSTOMER_ID。如果一個特定的記錄有PATIENT_ID我想PATIENTNAMERT_TICKET_PATIENT作爲NAME否則將舉行CUSTOMER_ID。如果是我想CUSTOMERNAME作爲名稱。

這裏我確定BILL_PATIENT_BILL必須有PATIENT_IDCUSTOMER_ID。 任何人都可以幫助我嗎?

回答

1

您還可以使用IF()選擇正確的價值觀,而不是構建從字符串查詢:

SELECT 
     BILL.BILL_NO AS BILLNO, 
     IF(BILL.PATIENT_ID IS NULL, cus.CUSTOMERNAME, pat.PATIENTNAME) AS NAME 
FROM 
     BILL_PATIENT_BILL AS BILL 
LEFT JOIN RT_TICKET_CUSTOMER cus ON BILL.CUSTOMER_ID = cus.ID 
LEFT JOIN RT_TICKET_PATIENT pat ON BILL.PATIENT_ID = pat.ID 

但是,它也有可能PREPARE從字符串的聲明和EXECUTE,但這種技術很容易以SQL注入,我只能disadvise這樣做:

在這裏讀到:Is it possible to execute a string in MySQL?

+0

感謝ü怪異。有結果。 – 2012-02-06 11:20:00