我试图基于发送到SELECT
条件的特定字符串来执行特定的IF
语句。例如,如果用户从下拉列表中选择支持,则将变量键发送到sql语句,并执行适当的SELECT
语句。
DECLARE @ strg
SET @strg = 'input string'
IF(SELECT * FROM tickets WHERE ticket_section = @strg)
BEGIN
SELECT
usr_users.uname AS `user`,
support_chat_user.message AS user_message,
support_chat_user.created AS user_chat_date,
support_ticket.`subject` AS ticket_subject,
support_ticket.`status` AS ticket_state,
support_ticket.created AS ticket_date,
support_ticket.modified AS updated_date,
tickets.state
FROM
tickets
INNER JOIN support_chat_user ON support_chat_user.tickets_id = tickets.tick_id
INNER JOIN support_ticket ON support_ticket.tickets_id = tickets.tick_id
INNER JOIN usr_users ON support_chat_user.reporter_id = usr_users.uid
WHERE
tickets.tick_id = '9' AND
usr_users.uid = '1'
END
IF EXISTS(SELECT * FROM tickets WHERE ticket_section = @strg)
BEGIN
SELECT
usr_users.uname AS `user`,
support_chat_user.message AS user_message,
support_chat_user.created AS user_chat_date,
support_ticket.`subject` AS ticket_subject,
tickets.state
FROM
tickets
INNER JOIN support_chat_user ON support_chat_user.tickets_id = tickets.tick_id
INNER JOIN support_ticket ON support_ticket.tickets_id = tickets.tick_id
INNER JOIN usr_users ON support_chat_user.reporter_id = usr_users.uid
WHERE
tickets.tick_id = '9' AND
usr_users.uid = '1'
END
答案 0 :(得分:0)
MySQL不支持IF
,除非您将代码放在编程块中。您的问题有点难以理解,因为文本中提到了一个查询,但是代码却是两个,看起来似乎是相同的。
您可以将条件逻辑移至查询中最外面的WHERE
子句:
SELECT u.uname AS `user`, scu.message AS user_message, scu.created AS user_chat_date,
st.`subject` AS ticket_subject, st.`status` AS ticket_state, st.created AS ticket_date, st.modified AS updated_date,
t.state
FROM tickets t JOIN
support_chat_user scu
ON scu.tickets_id = t.tick_id JOIN
support_ticket st
ON st.tickets_id = t.tick_id JOIN
usr_users u
ON scu.reporter_id = u.uid
WHERE t.tick_id = 9 AND -- presumably this is not numeric
u.uid = 1 AND -- presumably this is not numeric
EXISTS (SELECT 1 FROM tickets t2 WHERE t2.ticket_section = @strg)
我不确定这是您真正想要的。我怀疑你想要
WHERE t.tick_id = 9 AND -- presumably this is not numeric
u.uid = 1 AND -- presumably this is not numeric
(t.ticket_section = @strg OR @strg IS NULL)
但是,这仅仅是在推测您所描述的情况下有用的信息。
注意: