如果另一个select语句满足条件,则包括执行sql查询的条件

时间:2017-08-10 16:06:10

标签: mysql sql

我在执行查询时遇到问题。我有两个看起来像这样的SQL查询:

SELECT COUNT(clients_id) FROM users_clients WHERE users_id = 'sample';

SELECT name FROM clients JOIN users_clients ON clients.client_id = users_clients.clients_id WHERE users_clients.users_id = 123456;

我需要执行第二个sql语句,如果第一个等于或大于1.我可以只在一个语句中执行此查询吗?

3 个答案:

答案 0 :(得分:0)

也许:

SELECT .... second_query
WHERE
   .....
   AND (
       SELECT COUNT(clients_id) FROM users_clients WHERE users_id = 'sample'
   ) > 1

如果子查询的结果< = 1,则整个查询不返回任何行。实际上,MySql根本不会运行主(第二)查询。

答案 1 :(得分:0)

您可以使用exists

  SELECT name 
  FROM clients 
  JOIN users_clients ON clients.client_id = users_clients.clients_id 
  WHERE users_clients.users_id = 123456
  and exists(
    SELECT COUNT(clients_id) 
    FROM users_clients 
    WHERE users_id = 'sample'
    )
  ;

答案 2 :(得分:0)

SELECT name 
FROM clients 
JOIN users_clients 
ON clients.client_id = users_clients.clients_id 
WHERE users_clients.users_id = 123456
AND (SELECT COUNT(clients_id) FROM users_clients WHERE users_id = 'sample' ) > 1