[英]MySQL run one of the two sql queries depending on result of third query
I have three sql queries: 我有三个SQL查询:
1) SELECT * FROM table_name_1 WHERE user = 'user1' AND sub_name = '' AND name != 'some_name';
2) SELECT * FROM table_name_1 WHERE user = 'user1' AND sub_name = '';
3) SELECT DISTINCT role FROM table_name_1 where user = 'user1';
Here, can I combine these 3 queries to be able to run either query 1 or query 2 depending on result of query 3? 在这里,我可以结合这3个查询以根据查询3的结果运行查询1或查询2吗?
I can run query 3 first and take that output in a variable and depending on the value in that varaible can run either query 1 or 2. But I want to see if all this can be done purely in sql. 我可以先运行查询3,然后将该输出放入一个变量,然后根据该变量中的值运行查询1或2。但是我想看看是否所有这些操作都可以完全在sql中完成。
I tried it using IF but getting error as below, which I think is because I am not selecting any column after first SELECT. 我使用IF尝试了此操作,但收到如下错误,这是因为我没有在第一次SELECT之后选择任何列。 But I don't really need anything selected there:
但是我真的不需要选择任何东西:
mysql> SELECT IF(((select distinct role from table_name_1 where user = 'user1') = 'admin'),(SELECT name, display, good_high, critical_low, warning_low, warning_high FROM table_name_1 WHERE user = 'user1' AND sub_name = ''),(SELECT name, display, good_high, critical_low, warning_low, warning_high FROM table_name_1 WHERE user = 'user1' AND sub_name = '' AND name != 'some_name'));
ERROR 1241 (21000): Operand should contain 1 column(s)
mysql> SELECT IF(((select role from table_name_1 where user = 'user1' limit 1) = 'admin'),(SELECT name, display, good_high, critical_low, warning_low, warning_high FROM table_name_1 WHERE user = 'user1' AND sub_name = ''),(SELECT name, display, good_high, critical_low, warning_low, warning_high FROM table_name_1 WHERE user = 'user1' AND sub_name = '' AND name != 'some_name'));
ERROR 1241 (21000): Operand should contain 1 column(s)
mysql>
You can combine those queries with EXISTS: 您可以将这些查询与EXISTS结合使用:
SELECT *
FROM table_name_1
WHERE
user = 'user1'
AND sub_name = ''
AND (
(name != 'some_name')
OR EXISTS (SELECT role FROM table_name_1
WHERE user = 'user1' AND role='admin')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.