查询MySQL数据库以从另一个表中获取值

时间:2013-04-05 17:54:23

标签: mysql sql database database-design metadata

我有两个MySQL数据库表:

房车

-----------------------
| id  | status | name |
-----------------------
|  1  | active | mh 1 |
|  2  | active | mh 2 |
-----------------------

motorhome_meta

----------------------------------------------
| id  | motorhome_id | meta_key | meta_value |
----------------------------------------------
|  1  | 1            | size     | large      |
|  2  | 1            | fuel     | petrol     |
|  3  | 2            | size     | small      |
|  4  | 2            | fuel     | petrol     |
----------------------------------------------

我需要的是一个查询,它允许我从motorhome表中选择一行,其中包含motorhome_meta表中的值。或者换句话说,如果我在中选择行 标识为{1}的motorhome表。

----------------------------------------
| id  | status | name | size  | fuel   |
----------------------------------------
|  1  | active | mh 1 | large | petrol |
----------------------------------------

在某些情况下,我可能需要对任一表使用where语句,例如WHERE motorhome.status='active'WHERE motorhome_meta.meta_key='size'

2 个答案:

答案 0 :(得分:5)

您可以使用带CASE的聚合函数来创建数据行中的列:

select m.id,
  m.status,
  m.name,
  max(case when h.meta_key= 'size' then h.meta_value end) size,
  max(case when h.meta_key= 'fuel' then h.meta_value end) fuel
from motorhome m
inner join motorhome_meta h
  on m.id = h.motorhome_id
-- where m.id = 1
group by   m.id, m.status, m.name

SQL Fiddle with Demo。这给出了结果:

| ID | STATUS | NAME |  SIZE |   FUEL |
---------------------------------------
|  1 | active | mh 1 | large | petrol |
|  2 | active | mh 2 | small | petrol |

如果UNIQUE组合存在(motorhome_id, meta_key)约束,您也可以使用此变体:

select m.id,
  m.status,
  m.name,
  h1.meta_value  size,
  h2.meta_value  fuel
from motorhome m
left join motorhome_meta h1           -- or:  inner join
  on  m.id = h1.motorhome_id          -- depending on your need (or not)
  and h1.meta_key = 'size'            -- to show motorhomes
left join motorhome_meta h2           -- that have  only 'fuel'
  on  m.id = h2.motorhome_id          -- or only 'size'
  and h2.meta_key = 'fuel' ; 

请参阅:SQL-Fiddle-2

答案 1 :(得分:0)

问题更多的是Relational Division

SELECT  a.id,
        a.status,
        a.name,
        MAX(CASE WHEN b.meta_key= 'size' THEN b.meta_value END) size,
        MAX(CASE WHEN b.meta_key= 'fuel' THEN b.meta_value END) fuel
FROM    motorhome a
        INNER JOIN motorhome_meta b
            ON a.ID = b.motorhome_ID
WHERE   a.status = 'active' AND
        (
            (b.meta_key = 'size' AND b.meta_value = 'large') OR
            (b.meta_key = 'fuel' AND b.meta_value = 'petrol') 
        )
GROUP   BY a.id, a.status, a.name
HAVING  COUNT(*) = 2

输出

╔════╦════════╦══════╦═══════╦════════╗
║ ID ║ STATUS ║ NAME ║ SIZE  ║  FUEL  ║
╠════╬════════╬══════╬═══════╬════════╣
║  1 ║ active ║ mh 1 ║ large ║ petrol ║
╚════╩════════╩══════╩═══════╩════════╝