Reputation: 2626
I have made two tables. The first table holds the metadata of a file.
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 |
+-------+-------------+---------+------+---------+
The second table contains the "favourite" info about a particular file in the above table.
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 |
+--------+------+-----------------+----------------+
here "id' is a foreign key. The second table is showing which person has marked which document as his/her favourite. Eg the file abc.txt represented by id = 1 has been marked favourite (see column favouritedby) by ross and josh.
so what i wanna do is to get a table/view which shows the info as following -
+-------+-------------+---------+------+---------+---------------+
| 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 |
+-------+-------------+---------+------+---------+---------------+
How do i achieve this?
Upvotes: 1
Views: 83
Reputation: 33511
Use JOIN
(from the top of my head, no checks done):
SELECT filemetadata.id, filename, path, size, author, GROUP_CONCAT(favouritedby)
FROM filemetadata
LEFT JOIN filefav ON filemetadata.id=filefav.id GROUP BY filemetadata.id
Upvotes: 3
Reputation: 8109
Select A.*,B.favouritedby FROM filemetadata A Left join (Select id,Group_Concat(favouritedby) from filefav group by id) B ON A.
Id=B.Id
Upvotes: 2
Reputation: 4962
Create a view that creates a UNION of the two tables:
CREATE VIEW filefavs AS
SELECT * FROM filemetadata
UNION
SELECT * FROM filefav
Upvotes: -1