0

I have one table which stores tags for files. The tags can be of different types. There are many files, each with tags stored for them of different types.

columns: file, tagtype, tags

So let's say I have two rows for one file:

cyclist.jpg | date | 04-05-2012
cyclist.jpg | face | true

I would like to select into one row, all tags for a file, such that I have a mysql result:

cyclist.jpg 04-05-2012 true

At present I carry out two queries for the above, one for each tagtype. I want to know if I can do some kind of join, with the same table, on the same columns (tags), just based on one shared column (file).

4

1 回答 1

1

If you want to join automatically two rows that means that probably you can just create one row without spliting it:

file         | date       | face 
cyclist.jpg  | 04-05-2012 | true

Otherwise if you need to keep separate rows, just select all rows in one query:

$res = mysql_query("select * from tags where file='cyclist.jpg'");

and then iterate them to fulfil 'merged' record:

$res = mysql_query("select * from tags_table where file='cyclist.jpg'");

$mergedRow = array();

while ($row = mysql_fetch_assoc($res)) {
    foreach ($row as $rowKey => $rowValue) {
        if (!array_key_exists($rowKey, $mergedRow)) {
            $mergedRow[$rowKey] = $rowValue;
        }
    }
}

Edit:

As promised here's a sample of joining two rows into one with single query, however I would still recommend $mergedRow approach in PHP to merging them :)

CREATE TABLE `files_table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `tag_type` enum('PARENT','CHILD') NOT NULL DEFAULT 'PARENT',
  `date` date DEFAULT NULL,
  `file` varchar(255) NOT NULL DEFAULT '',
  `face` smallint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

Then you can 'pair' PARENT-CHILDREN sets with:

SELECT t1.file, t1.date, t2.face
    FROM files_table AS t1 JOIN files_table AS t2 ON (t1.file = t2.file)
    WHERE t1.tag_type = 'PARENT' AND t2.tag_type = 'CHILD'
    GROUP BY file
于 2012-05-04T18:39:50.813 回答