MySQL数据库加入查询

时间:2015-04-02 16:04:28

标签: mysql sql database

请有人建议如何根据表A和表B信息为下面的结果编写mySQL查询。

Table A
=======

ID | Product
------------
1  | A
2  | B
3  | C

Table B
=======

ID | Link | Extra Field | Extra Value
-------------------------------------
1  |  1   | Tax         | Yes
2  |  1   | Photo       | No
3  |  2   | Tax         | Yes
4  |  2   | Photo       | Yes
5  |  3   | Tax         | No
6  |  3   | Photo       | Yes

Result
======

Product | Tax | Photo
---------------------
A       | Yes | No
B       | Yes | Yes
C       | No  | Yes

1 个答案:

答案 0 :(得分:0)

一种方法是使用条件聚合的joingroup by查询。

select a.product,
       max(case when field1 = 'tax' then field2 end) as tax,
       max(case when field1 = 'photo' then field2 end) as photo
from a join
     b
     on a.id = b.link
group by a.product;