sljtfyt
2018-06-15 07:54
采纳率: 100%
浏览 8.6k

SQL 两个无关的查询结果如何合并成多列

图片说明

表1字段A、B、C;表2字段D、E、F;
如何根据表1和表2信息,生成表3信息。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

7条回答 默认 最新

  • threenewbee 2018-06-15 08:15
    已采纳
     select a.*, b.* from (select ROW_NUMBER() over(order by A) as id, * from table1) a
    left join (select ROW_NUMBER() over(order by D) as id, * from table2) b on a.id = b.id
    
    已采纳该答案
    打赏 评论
  • 程序员的键盘 2018-06-19 02:36

    select * from table1
    left join table2 on 1=1

    3 打赏 评论
  • threenewbee 2018-06-15 08:16

    图片说明

    打赏 评论
  • threenewbee 2018-06-15 08:19

    稍微修改下

     select a.A, a.B, a.C, b.D, b.E, b.F from (select ROW_NUMBER() over(order by A) as id, * from table1) a
    left join (select ROW_NUMBER() over(order by D) as id, * from table2) b on a.id = b.id"
    
    打赏 评论
  • threenewbee 2018-06-15 08:20

    图片说明

    打赏 评论
  • threenewbee 2018-06-15 08:20

    完整C#代码

     using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    
    namespace Q692230
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"C:\\Documents and Settings\\user1\\My Documents\\Q692230DB.mdf\";Integrated Security=True;Connect Timeout=30;User Instance=True");
                conn.Open();
                string sql =
    @"select a.A, a.B, a.C, b.D, b.E, b.F from (select ROW_NUMBER() over(order by A) as id, * from table1) a
    left join (select ROW_NUMBER() over(order by D) as id, * from table2) b on a.id = b.id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                DataSet ds = new DataSet();
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                ad.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
            }
        }
    }
    
    
    打赏 评论
  • whitebrow 2018-06-21 15:15

    mysql亲测可用, 其中 order by ... limit 10, 可以去掉不用的。

    select X.A, X.B, X.C, Y.D, Y.E, Y.F from
    (Select (@rowNum:=@rowNum+1) as rowNo, A, B, C
    From t1, (Select (@rowNum :=0) ) x1
    Order by t1.id desc limit 10) X
    left join
    (Select (@rowNum2:=@rowNum2+1) as rowNo, D, E, F
    From t2,
    (Select (@rowNum2 :=0) ) y1
    Order by t2.id desc limit 10) Y
    on X.rowNo = Y.rowNo;

    打赏 评论

相关推荐 更多相似问题