动态查询字符串

时间:2012-02-06 10:30:37

标签: mysql

我想根据一个特定的列值在from子句中添加一些动态内容。 可能吗? 例如,

 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我希望PATIENTNAME RT_TICKET_PATIENT中的CUSTOMER_ID作为NAME,则会保留CUSTOMERNAME。如果我想要BILL_PATIENT_BILL作为NAME。

我确信PATIENT_ID必须有CUSTOMER_ID或{{1}}。 谁能帮我?

1 个答案:

答案 0 :(得分: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注入,我只能这样做了:

请在此处阅读:Is it possible to execute a string in MySQL?