根据条件和用户输入的MySQL执行Select语句

时间:2018-10-06 14:54:42

标签: php sql mysqli

我试图基于发送到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

1 个答案:

答案 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)

但是,这仅仅是在推测您所描述的情况下有用的信息。

注意:

  • 表别名使查询更易于编写和读取(适当的缩进也是如此)。
  • 数字常数不应使用单引号引起来。我猜这些ID确实是数字。如果它们是字符串,则单引号是合适的。