简体   繁体   English

SQL select语句始终返回4条记录

[英]Sql select statement always returns 4 records

I am trying to solve a SQL query where i ALWAYS get 4 records, if one of the records does not exist it can be null. 我正在尝试解决一个SQL查询,其中我总是获得4条记录,如果其中一条记录不存在,则可以为null。

Let's say i have the following table named names 假设我有一个名为names的下表

Name id:       Name:
1              John
2              Mike
3              Marcel

Now i will use the following sql query: 现在,我将使用以下sql查询:

Select names.name from names

I will get the following results 我会得到以下结果

John
Mike
Marcel

But what i am trying to achieve is: 但是我想要实现的是:

John
Mike
Marcel
NULL

so i always want 4 records even when there are only 3. Its not an option to add a 4th. 因此,即使只有3个,我也总是想要4个记录。它不是添加第4个的选项。

Someone know how to achieve this? 有人知道如何实现这一目标吗?

You can do this with a union all and order by . 您可以使用union all并按order by You don't specify the database, but the following gives one method: 您没有指定数据库,但是以下提供了一种方法:

select name
from (select name
      from table t
      limit 4
     ) union all
     (select null union all
      select null union all
      select null union all
      select null
     )
order by (case when name is not null then 1 else 0 end) desc
limit 4;

Some aspects of the syntax might vary, depending on the database, but the idea is the same. 语法的某些方面可能会有所不同,具体取决于数据库,但是想法是相同的。

You didn't specify your DBMS so this is ANSI SQL: 您没有指定DBMS,所以这是ANSI SQL:

with numbers (nr) as (
  values (1),(2),(3),(4)
)
select names.name
from numbers  
  left join (
      select id,
             name,
             row_number() over (order by id) as rn
      from names)
  ) names on names.rn = numbers.nr;

If you don't know if there are 3 or 4 rows in the table, you can apply a limit the join condition: on names.rn = numbers.nr and names.nr <= 3 . 如果您不知道表中是否有3或4行,则可以对连接条件施加限制: on names.rn = numbers.nr and names.nr <= 3 This will ensure that you will never retrieve more than three rows from the names table. 这将确保您从names表中检索的行永远不会超过三行。

If you you only care about the ids 1,2,3 and there will never be other IDs you can do something like this: 如果您只关心ID 1,2,3,并且永远不会有其他ID,则可以执行以下操作:

with numbers (nr) as (
  values (1),(2),(3),(4)
)
select names.name
from numbers  
  left join names on names.id = numbers.nr;

You can replace 4 with any value that will definitely not exist in your table. 您可以用表中绝对不存在的任何值替换4

You can try with simple SQL Query. 您可以尝试使用简单的SQL查询。 Assuming that you are using SQL Server. 假设您正在使用SQL Server。

SELECT TOP 4
   id,name
FROM
  (SELECT id, name from t
  UNION ALL
    SELECT TOP 4
         NULL,null
     FROM sys.columns) T

SQLFIDDLE SQLFIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM