如果第一个 SELECT 返回空集,则另一个 SELECT

发布于 2024-09-30 03:35:38 字数 524 浏览 2 评论 0原文

这是我的表:

  id    id_1     camp 
 1        0         x1     
 2        0         x2
 3        0         x3
 4        1         x4
 5        1         x5
 6        1         x6
 7        3         x7
 8        3         x8
 9        3         x9 

我需要一个 SQL,如果没有 id_1 为“x”的行,它应该返回那些 id_1 为 0 的行。例如,如果我选择 id_1 = 2,它将返回 select * whereid_1= 0

这可以在一份声明中完成吗?我在使用 IF EXISTS 或 CASE 时运气不佳。语法...

一如既往的感谢

This is my table:

  id    id_1     camp 
 1        0         x1     
 2        0         x2
 3        0         x3
 4        1         x4
 5        1         x5
 6        1         x6
 7        3         x7
 8        3         x8
 9        3         x9 

I am in need of a SQL that, if there are no rows with id_1 of "x", it should return those with id_1 of 0. For example, if I were to select id_1 = 2, it would return the select * whereid_1= 0.

Could this be done in one statement? I had little luck using IF EXISTS or CASE. Syntax...

Thanks, as always

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云裳 2024-10-07 03:35:38
SELECT SQL_CALC_FOUND_ROWS id, id_1, camp
FROM your_table
WHERE id_1 = 2

UNION ALL

SELECT id, id_1, camp
FROM your_table
WHERE 
FOUND_ROWS() = 0 AND id_1 = 0;
SELECT SQL_CALC_FOUND_ROWS id, id_1, camp
FROM your_table
WHERE id_1 = 2

UNION ALL

SELECT id, id_1, camp
FROM your_table
WHERE 
FOUND_ROWS() = 0 AND id_1 = 0;
沉睡月亮 2024-10-07 03:35:38
  SELECT * 
  FROM mytable 
  WHERE id_1 = 2 
UNION ALL
  SELECT * 
  FROM mytable 
  WHERE id_1 = 0 
    AND NOT EXISTS 
        ( SELECT * 
          FROM mytable 
          WHERE id_1 = 2
        )
  SELECT * 
  FROM mytable 
  WHERE id_1 = 2 
UNION ALL
  SELECT * 
  FROM mytable 
  WHERE id_1 = 0 
    AND NOT EXISTS 
        ( SELECT * 
          FROM mytable 
          WHERE id_1 = 2
        )
楠木可依 2024-10-07 03:35:38

不要忽略在代码中而不是 SQL 中实现此逻辑的方法。

Don't ignore a way to implement this logic in your code instead of SQL.

锦欢 2024-10-07 03:35:38

如果没有 id_1 为“x”的行,它应该返回 id_1 为 0 的行。您可以尝试这样做 -

IF EXISTS ( SELECT * FROM mytable WHERE id_1 = 2 ) 
    SELECT * FROM mytable WHERE id_1 = 2 
ELSE
    SELECT * FROM mytable WHERE id_1 = 0

If there are no rows with id_1 of "x", it should return those with id_1 of 0. You can try this -

IF EXISTS ( SELECT * FROM mytable WHERE id_1 = 2 ) 
    SELECT * FROM mytable WHERE id_1 = 2 
ELSE
    SELECT * FROM mytable WHERE id_1 = 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文