从两个表中选择而不是订购它

时间:2012-03-01 01:12:13

标签: php mysql

我有4个表,default_table,table_a,table_b,table_c,每个都有两列,
我想从所有表中选择nameid然后对其进行排序,
我试试"SELECT Name,ID FROM default_table, table_a, table_b, table_c ORDER BY Name"
但这给了我错误,所以有人可以帮我解决这个问题,我需要sql或php中的代码,甚至是javascript,如果可以的话

3 个答案:

答案 0 :(得分:5)

由于在结合后应用order by,您可以执行以下操作:

select id, name from default_table
    union all select id, name from table_a
    union all select id, name from table_b
    union all select id, name from table_c
order by name

您的问题是,您正在制作所有表格数据的笛卡尔积,因此无法找出 idname的意思。即使可能,由于乘法效应,你会得到 way 更多的行。您只想通过所有行添加到输出中来加入数据。


进一步解释这个区别,假设你有两个表:

table1          table2
======          ======
id     name     id     name
--     ----     --     ------
 1     pax       1     jill
 2     bob       2     debbie
 3     joe

查询:

select a.id, a.name, b.id, b.name from table1 a, table2 b

(笛卡儿产品)会给你:

1 pax 1 jill
1 pax 2 debbie
2 bob 1 jill
2 bob 2 debbie
3 joe 1 jill
3 joe 2 debbie

(行数是各行数的乘积)而:

select id, name from table1
union all
select id, name from table2

(工会)会给你:

1 pax
2 bob
3 joe
1 jill
2 debbie

(行数是各行数的总和)。

答案 1 :(得分:1)

我想你需要UNION(或UNION ALL):

SELECT *
FROM
  ( SELECT Name, ID 
    FROM default_table
  UNION ALL
    SELECT Name, ID 
    FROM table_a
  UNION ALL
    SELECT Name, ID 
    FROM table_b
  UNION ALL
    SELECT Name, ID 
    FROM table_c
  ) AS un
ORDER BY Name

答案 2 :(得分:0)

尝试这样的事情

SELECT 
    t1.name AS t1_name, t1.id AS t1_id, 
    t2.name AS t2_name, t2.id AS t2_id, 
    t3.name AS t3_name, t3.id AS t3_id, 
    t4.name AS t4_name, t4.id AS t4_id
FROM 
    default_table AS t1,
    table_a AS t2,
    table_b AS t3,
    table_c AS t4
ORDER BY t1.name