在许多表上按ORDER BY SQL

时间:2016-12-06 06:47:16

标签: mysql sql sql-server

我有这张桌子

private static void ReadPropertiesRecursive<Tt>(Tt obj, Type type, List<string> prefixes)
{

    foreach (PropertyInfo property in type.GetProperties())
    {
        if (property.PropertyType.GetTypeInfo().IsClass && property.PropertyType != typeof(string))
        {
            prefixes.Add(property.Name);
            var val = property.GetValue(obj);
            if (val == null)
                val = Activator.CreateInstance(property.PropertyType);
            property.SetValue(obj, val);
            ReadPropertiesRecursive(val, property.PropertyType, prefixes);
            prefixes.Remove(property.Name);
        }
        else
        {
            var propertyFullName = prefixes != null && prefixes.Count > 0 ? $"{prefixes.Aggregate((i, j) => i + "." + j)}.{property.Name}" : property.Name;

            property.SetValue(obj, dic[propertyFullName]);

            Console.WriteLine(propertyFullName);
        }
    }
}

和其他像这样的表

Table1
 id  |  name  |
  1  |   a    |
  2  |   c    |

如何将这两个表排序为结果

  

a b c d

DONE READING THIS但它只会给我这个结果

  

a c b d

当我尝试这个时

Table2
 id  |  name  |
  1  |   b    |
  2  |   d    |

4 个答案:

答案 0 :(得分:5)

您可以尝试改为使用两个表中的UNION

SELECT id, name
FROM Table1
UNION ALL
SELECT id, name
FROM Table2
ORDER BY name

如果要保留有关每条记录的原始来源的信息,可以为其添加一列:

SELECT id, name, 't1' AS source
FROM Table1
UNION ALL
SELECT id, name, 't2'
FROM Table2
ORDER BY name

<强>更新

如果Codeigniter不支持UNION开箱即用,您始终可以将上述查询放入字符串并以原生方式执行:

$sql = "SELECT id, name FROM Table1 UNION ALL SELECT id, name FROM Table2 ORDER BY name";
$this->db->query($sql);

答案 1 :(得分:1)

SELECT *
INTO #TEMP_TBL
FROM Table1 AS t1 
JOIN Table2 AS t2 
ON t2.id = t1.id

SELECT *
FROM #TEMP_TBL
ORDER BY ID, NAME

DROP TABLE #TEMP_TBL

答案 2 :(得分:1)

如果您想使用加入,请尝试以下查询

select * from (select x.* from table1 as x  left join table2 as y on x.id = y.id) as z order by z.name;

答案 3 :(得分:1)

我们也可以使用它:

SELECT * FROM (
    SELECT id, NAME FROM Table1
    UNION ALL
    SELECT id, NAME FROM Table2) t ORDER BY name