根据条件和用户输入执行select语句

jobtbby3  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(403)

我正试图允许一个特定的 SELECT 基于发送到 IF 条件。例如,如果用户从下拉列表中选择了support,则会向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
s3fp2yjn

s3fp2yjn1#

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)

然而,这仅仅是关于在你描述的情况下什么是有用的知情推测。
笔记:
表别名使查询更易于编写和读取(正确的缩进也是如此)。
数字常量不应该用单引号引起来。我猜身份证真的是数字。如果它们是字符串,那么单引号是合适的。

相关问题