在数据库中组合两个表

时间:2013-07-11 07:31:22

标签: mysql sql database database-design database-schema

我已经制作了两张桌子。第一个表保存文件的元数据。

create table filemetadata (
id varchar(20) primary key ,
filename varchar(50),
path varchar(200),
size varchar(10),
author varchar(50)
) ;

+-------+-------------+---------+------+---------+
| id    | filename    | path    | size | author  | 
+-------+-------------+---------+------+---------+
| 1     | abc.txt     | c:\files| 2kb  | eric    | 
+-------+-------------+---------+------+---------+
| 2     | xyz.docx    | c:\files| 5kb  | john    | 
+-------+-------------+---------+------+---------+
| 3     | pqr.txt     |c:\files | 10kb | mike    | 
+-------+-------------+---------+------+---------+

第二个表包含上表中特定文件的“收藏”信息。

create table filefav (
fid varchar(20) primary key ,
id varchar(20),
favouritedby varchar(300),
favouritedtime varchar(10),
FOREIGN KEY (id) REFERENCES filemetadata(id) 
) ;

+--------+------+-----------------+----------------+
| fid    | id   | favouritedby    | favouritedtime | 
+--------+------+-----------------+----------------+
| 1      | 1    | ross            | 22:30          | 
+--------+------+-----------------+----------------+
| 2      | 1    | josh            | 12:56          | 
+--------+------+-----------------+----------------+
| 3      | 2    | johny           | 03:03          | 
+--------+------+-----------------+----------------+
| 4      | 2    | sean            | 03:45          | 
+--------+------+-----------------+----------------+

这里“id”是外键。 第二个表格显示哪个人将哪个文件标记为他/她的最爱。 例如,由id = 1表示的文件abc.txt已经被ross和josh标记为收藏(参见列favouritedby)。

所以我想做的是获得一个表/视图,显示如下信息 -

+-------+-------------+---------+------+---------+---------------+
| id    | filename    | path    | size | author  | favouritedby  |
+-------+-------------+---------+------+---------+---------------+
| 1     | abc.txt     | c:\files| 2kb  | eric    | ross, josh    |
+-------+-------------+---------+------+---------+---------------+
| 2     | xyz.docx    | c:\files| 5kb  | john    | johny, sean   |
+-------+-------------+---------+------+---------+---------------+
| 3     | pqr.txt     |c:\files | 10kb | mike    | NULL          |
+-------+-------------+---------+------+---------+---------------+

我如何实现这一目标?

3 个答案:

答案 0 :(得分:3)

使用JOIN(从我的头顶开始,没有做任何检查):

SELECT filemetadata.id, filename, path, size, author, GROUP_CONCAT(favouritedby) 
FROM filemetadata 
LEFT JOIN filefav ON filemetadata.id=filefav.id GROUP BY filemetadata.id

答案 1 :(得分:2)

Select A.*,B.favouritedby FROM filemetadata A Left join (Select id,Group_Concat(favouritedby) from filefav group by id) B ON A.标识= B.Id

答案 2 :(得分:-1)

创建一个视图,创建两个表的UNION:

CREATE VIEW filefavs AS
SELECT * FROM filemetadata 
UNION
SELECT * FROM filefav