如何将一个表的行与另一个表的键和值联接

时间:2019-02-18 20:40:29

标签: mysql codeigniter

我有2个表,一个表(团队)包含基本的团队信息,另一个表(Teammeta)具有构造为键和值的所有其他信息。我想要一个查询,其中public function num_rows(){ $this->db->from('tbl_category'); return $this->db->count_all_results(); } teams.id匹配,并以键和所需结果中给出的值的形式输出结果。

表格:团队

| id | Name       |
|----|------------|
| 1  | Glagiators |
| 2  | Sultans    |

TABLE: Teammeta

| tmeta_id | team_id | meta_key | meta_value |
|----------|---------|----------|------------|
| 1        | 1       | player1  | Joe        |
| 2        | 1       | player2  | Mark       |
| 3        | 2       | player1  | Smith      |
| 4        | 2       | player2  | Drake      |

表:所需结果

Array
(
    [0] => stdClass Object
        (
            [Name] => Glagiators 
            [player1] => Joe
            [player2] => Mark
        )
    [1] => stdClass Object
        (
            [Name] => Sultans
            [player1] => Smith
            [player2] => Drake
        )
)

2 个答案:

答案 0 :(得分:0)

对不起,第一次误读。怎么样:

SELECT TeamsTable.Name, TeamMetaTableP1.meta_value AS player1, TeamMetaTableP2.meta_value AS player2
FROM teams AS TeamsTable
JOIN (SELECT * FROM teammeta) AS TeamMetaTableP1 ON TeamsTable.id = TeamMetaTableP1.team_id
JOIN (SELECT * FROM teammeta) AS TeamMetaTableP2 ON TeamsTable.id = TeamMetaTableP2.team_id
WHERE TeamMetaTableP1.meta_key = 'player1'
AND TeamMetaTableP2.meta_key = 'player2'

答案 1 :(得分:0)

SELECT Teams.Name, Teammeta.meta_key, Teammeta.meta_value FROM Teams INNER JOIN Teammeta ON Teams.id = Teammeta.team_id

将返回结果为

+-------------+-------------------+---------------------+
| Teams.Name  | Teammeta.meta_key | Teammeta.meta_value |
+-------------+-------------------+---------------------+
| Galligators | player1           | Joe                 |
| Galligators | player2           | Mark                |
| Sultans     | player1           | Smith               |
| Sultans     | player2           | Drake               |
+-------------+-------------------+---------------------+

您需要在此之后进行一些解析,以获取正确的格式。
这可能也有帮助:https://stackoverflow.com/a/12808230/9919745
编辑:
数据转换代码

while($row = $result->fetch_assoc()){
  $name = $row['Teams.Name'];
  $data[$name][$row['Teammeta.meta_key']] = $data[$name][$row['Teammeta.meta_value']];
}