我想根据一个特定的列值在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_ID
或CUSTOMER_ID
。如果特定记录PATIENT_ID
我希望PATIENTNAME
RT_TICKET_PATIENT
中的CUSTOMER_ID
作为NAME,则会保留CUSTOMERNAME
。如果我想要BILL_PATIENT_BILL
作为NAME。
我确信PATIENT_ID
必须有CUSTOMER_ID
或{{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注入,我只能这样做了: