2012-01-31 37 views
0

如我的示例中可以组合两个表吗?组合两个表而不重复的MySQL

表中的一个:

bibid -- fieldid -- fied_data 
400 ----- 10 ------- 107 
400 ------ 5 -------- 1950 
400 ------ 3 -------- USA 
405 ------ 5 -------- 1997 
405 ----- 10 -------- 90 
405 ------ 3 -------- RUSSIA 

表二:

bibid -------- name 
400 --- Postman Always Rings Twice 
405 --- Postman is a very good person 

那结果将是:

bibid --------- name --------------------------length ----------year ---------- country 
400 -- Postman Always Rings Twice --------------107------------1950 ------------USA 
405 -- Postman is a very good person -----------90-------------1997 ------------RUSSIA 

回答

0

使用连接来获取数据。

SELECT one.bibid, 
    two.name, 
    one_10.fied_data as length, 
    one_5.fied_data as year, 
    one_3.fied_data as country 
from table_two two 
LEFT OUTER JOIN table_one one 
ON one.bibid = two.bibid 
LEFT OUTER JOIN table_one one_3 
ON one.bibid = one_3.bibid 
AND one_3.fieldid = 3 
LEFT OUTER JOIN table_one one_5 
ON one.bibid = one_5.bibid 
AND one_5.fieldid = 5 
LEFT OUTER JOIN table_one one_10 
ON one.bibid = one_10.bibid 
AND one_10.fieldid = 10 

但它会更好,一定要规范你的数据...

BTW:你的意思是field_data代替fied_data?

+0

它的工作原理,但重复每个bibid三次。受到帮助。非常感谢! – 2012-01-31 20:32:00

+0

Offcourse。然后做两个LOJ一个而不是一个LOJ两个编辑的答案。 – Konerak 2012-02-01 06:09:17

0

请尝试以下查询:

select o.bibid, t.name name, 
(case when o.fieldid = 10 then o.fied_data end) length, 
(case when o.fieldid = 5 then o.fied_data end) year, 
(case when o.fieldid = 3 then o.fied_data end) countrty 
from table_one o, table_two t 
where o.bibid = t.bibid 
group by o.bibidid, t.name 
+0

谢谢,但它只返回一个含义:长度,年,国家 – 2012-01-31 20:29:39

0

看一看group_cancat,我的MySQL语法太生疏为您提供一个适当的例子。在T-SQL的土地上呆了太久。这里的一些伪:

  1. 子查询SELECT GROUP_CONCAT(fied_data) FROM T1 GROUP BY bibid
  2. 外部查询SELECT [Whatever] FROM T2 JOIN T1 ON ...

基本上你是组串联的* fied_data *,然后查询结果集的加入,并在bibid。