在两个表中合并数据SQL

时间:2018-11-19 00:39:47

标签: mysql sql join

我敢肯定,这是一个非常基本的问题,但我仍然会陷入困境:

Table A - image_number, camera_type, total_sales
Table B - image_number, keyword

表A的每个image_number有一个ROW-例如:

image_number="AXJ789, camera_type="Nikon", total_sales=678
image_number="JIJ123", camera_type="Canon", total_sales=999
image_number="KNI908", camera_type="Sony", total_sales=565

表B的每个image_number有许多行-例如:

image_number="AXJ789", keyword = "rain"
image_number="AXJ789", keyword = "mountain"
image_number="AXJ789", keyword = "grass"
image_number="AXJ789", keyword = "cloud"

我想要做的是联接两个表,以便生成以下输出:

  

image_number =“ AXJ789”,camera_type = 678,camera_type =“ Nikon”,关键字(1)=“雨”,关键字(2)=“山”,关键字(3)=“草”,关键字(4) =“云”

换句话说,我希望表A的每个ROW中都有所有项+表B中的所有项。对于表A中的每个image_number,表B或50中可能没有“关键字”关键字-取决于图片。

当我进行INNER JOIN时,当然可以从表B中获得一个“关键字”,但是我不知道如何获得所有这些。

2 个答案:

答案 0 :(得分:1)

您可以将关键字连接在一起:

select a.*,
       (select group_concat(b.keyword)
        from b
        where b.image_number = a. image_number
       ) as keywords
from a;

这将创建一个以逗号分隔的关键字列表。 (在MySQL中)这比尝试将它们放在单独的列中要简单得多。实际上,如果您想要单独的列,我可能建议解析此结果:

select a.*,  -- or whatever columns you want
       substring_index(keywords, ',' 1) as keyword1,
       substring_index(substring_index(keywords, ',' 2), ',', -1) as keyword2,
       substring_index(substring_index(keywords, ',' 3), ',', -1) as keyword3,
       substring_index(substring_index(keywords, ',' 4), ',', -1) as keyword4
from a left join 
     (select b.image_number, group_concat(b.keyword) as keywords
      from b
      group by b.image_number
     ) b
     on b.image_number = a. image_number;

答案 1 :(得分:0)

您可以使用GROUP_CONCATJOIN为每个图像生成一个逗号分隔的关键字列表(但如果图像可能没有关键字,则使用LEFT JOIN)。

SELECT a.*, GROUP_CONCAT(b.keyword) AS keyword_list
FROM a
JOIN b on b.image_number = a.image_number
GROUP BY a.image_number

输出示例数据:

image_number    camera_type     total_sales     keyword_list
AXJ789          Nikon           678             rain,mountain,grass,cloud

Demo on dbfiddle

然后您可以将其解析为应用程序中的一个数组,例如在PHP中(如果您已将行读入$row中):

$keywords = explode(',', $row['keyword_list']);
print_r($keywords);

输出:

Array
(
    [0] => rain
    [1] => mountain
    [2] => grass
    [3] => cloud
)