MySQL根据第三个查询的结果运行两个sql查询之一

时间:2015-10-02 17:01:47

标签: mysql

我有三个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';

在这里,我可以将这3个查询组合起来,以便能够根据查询3的结果运行查询1或查询2吗?

我可以先运行查询3并将该输出放在变量中,并且根据该变量中的值可以运行查询1或2。 但我想看看是否所有这些都可以完全在sql中完成。

我尝试使用IF但是得到如下错误,我认为这是因为我在第一次选择SELECT后没有选择任何列。但我真的不需要在那里选择任何东西:

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>

1 个答案:

答案 0 :(得分:3)

您可以将这些查询与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')
  )