如何编写mysql查询以准确返回4行

我想要显示表格中的4行。 我有使用以下查询

SELECT field_name FROM tbl_name WHERE col_name ='value'LIMIT 4;

该表包含4个以上的值意味着它能够完美显示前4行。 但它少于4行意味着我需要结果为以下结果

  • 它仅显示2行意味着
  • FIELD_NAME
    ROW1
    2行
    2行
    ROW1

  • 它仅显示3行意味着
  • FIELD_NAME
    ROW1
    2行
    ROW3
    ROW1

    我怎样才能得到这个结果?


    像这样尝试

    Select * from (
    
    select * from tbl_name WHERE col_name = 'value' LIMIT 4
    union all 
    select * from tbl_name WHERE col_name = 'value' LIMIT 4
    union all
    select * from tbl_name WHERE col_name = 'value' LIMIT 4
    union all
    select * from tbl_name WHERE col_name = 'value' LIMIT 4) as table1   LIMIT 4
    

    不是一个很好的解决方案,但它应该可以工作:您可以使用UNION ALL重复查询4次,并限制为4个结果:

    SELECT * FROM (
        SELECT field_name FROM tbl_name WHERE col_name = 'value' LIMIT 4;
        UNION ALL
        SELECT field_name FROM tbl_name WHERE col_name = 'value' LIMIT 4;
        UNION ALL
        SELECT field_name FROM tbl_name WHERE col_name = 'value' LIMIT 4;
        UNION ALL
        SELECT field_name FROM tbl_name WHERE col_name = 'value' LIMIT 4;
    ) a LIMIT 4
    

    SELECT Column_Name
    FROM (
    SELECT Column_Name, ROW_NUMBER() OVER (ORDER BY Column_Name) AS RowNum
    FROM [dbo].[AttendanceLog]
    ) AS MyDerivedTable
     WHERE MyDerivedTable.RowNum BETWEEN 1 and 4
    
    链接地址: http://www.djcxy.com/p/75333.html

    上一篇: How to write the mysql query for return 4 rows exactly

    下一篇: Select from mysql, and count from other row