查询连接多个表

时间:2013-12-30 13:18:53

标签: sql-server sql-server-2008

我的数据库包含'costumers'idname。我有一个单独的数据库,其自定义表名称格式为table_customer_id_1table_customer_id_2,... n和列idpricedatetime(每个表的名称包含表'costumers'中每行的id)

查询表'costumers'并从表costumers获取客户名称以及每个table_customer_id_X的最新订单日期的最快方法是什么?

很抱歉我的英语不是很好,我不知道你是否能理解我的要求! :)

2 个答案:

答案 0 :(得分:0)

尝试类似这样的事情

select 
a.name, 
b.DateTime, 
c.datetime
from customer a
inner join tbl_customer_id1 b  on b.id=a.id
inner join tbl_customer_id2 c on c.id=a.id 
where a.name like '%Customer name%' 
order by b.datetime , c.datetime

答案 1 :(得分:0)

CREATE TABLE #Customers (id int, name varchar(10))
CREATE TABLE #Table_Customer_id_1 (id int, price decimal(18,2), datetimefield datetime)
CREATE TABLE #Table_Customer_id_2 (id int, price decimal(18,2), datetimefield datetime)
CREATE TABLE #Table_Customer_id_3 (id int, price decimal(18,2), datetimefield datetime)

INSERT INTO #Customers VALUES (1, 'Test1'), (2, 'Test2'), (3, 'Test3')

INSERT INTO #Table_Customer_id_1 VALUES 
  (1, 1.1, '2013-01-01'),
  (2, 1.2, '2013-01-02'),
  (3, 1.3, '2013-01-03'),
  (4, 1.4, '2013-01-04')

INSERT INTO #Table_Customer_id_2 VALUES 
  (1, 2.1, '2013-02-01'),
  (2, 2.2, '2013-02-02'),
  (3, 2.3, '2013-02-03'),
  (4, 2.4, '2013-02-04')

INSERT INTO #Table_Customer_id_3 VALUES 
  (1, 3.1, '2013-03-01'),
  (2, 3.2, '2013-03-02'),
  (3, 3.3, '2013-03-03'),
  (4, 3.4, '2013-03-04')

DECLARE @SQL nvarchar(max)

;WITH CTE AS(
  SELECT 'SELECT name, LastOrder FROM #Customers INNER JOIN (SELECT Max(datetimefield) AS
    LastOrder, ' + CONVERT(varchar(5),id) + ' AS CustID FROM #Table_Customer_id_' + 
    CONVERT(varchar(5),id) + ') Tab ON #Customers.id = Tab.CustID WHERE id = ' + 
    CONVERT(varchar(5),id) + '' AS SqlStatement FROM #Customers
)
SELECT @SQL = STUFF((SELECT ' UNION ALL ' + SqlStatement FROM CTE FOR XML PATH('')),1,11,'') 

EXEC sp_executesql @SQL

--DROP TABLE #Customers
--DROP TABLE #Table_Customer_id_1
--DROP TABLE #Table_Customer_id_2
--DROP TABLE #Table_Customer_id_3