尝试连接两个表,一个命令首先获得标记行

时间:2016-01-10 14:22:13

标签: mysql sql

我有这两个表:

prt_gebouw

id  | name
----+------------
1   | Building A
2   | Building B
3   | Building C

prt_image

id  | building_id   | name      | is_primary
----+---------------+-----------+------------
1   | 1             | img1.jpg  | 0
2   | 1             | img2.jpg  | 0
3   | 2             | img3.jpg  | 0
4   | 1             | img4.jpg  | 1
5   | 2             | img5.jpg  | 1

正如你在这里看到的,一些建筑物有一个以上的图像而一些建筑物没有。当建筑物有一个或多个图像时,只能将一个图像标记为主要图像;可以,因为这不是强制性的。

现在,我要做的是列出所有建筑物(每个建筑物一次)并将其与图像表连接,最好是主图像,如果没有图像可以找到空单元格。

首先我尝试了这个:

SELECT
    pgb.id,
    pgb.name,
    img.id AS image_id,
    img.name AS image_name,
    img.is_primary AS is_primary
FROM
    prt_gebouw pgb
    LEFT JOIN prt_image img ON pgb.id = img.object_id AND img.kind = 'object'
GROUP BY pgb.id
ORDER BY img.is_primary DESC, pgb.id ASC;

我怀疑分组是在排序之前完成的,因为错误的图像与每个具有多个图像的建筑物相连("错误"在这里:不是主要的)。

然后我尝试了:

SELECT
    pgb.id,
    pgb.name,
    img.id AS image_id,
    img.name AS image_name,
    img.is_primary
FROM
    prt_gebouw pgb
    LEFT JOIN (SELECT * FROM prt_image ORDER BY is_primary DESC) AS img ON img.object_id = pgb.id
ORDER BY pgb.id ASC;

我希望每个建筑物首先列出主要图像,但不是这样。我怀疑这也是上一个查询中的问题,但是呢? 而且,更重要的是,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为相关的子查询可能更容易满足您的需求:

select pgb.*,
       (select i.id
        from prt_image i
        where i.object_id = pgb.id and i.kind = 'object'
        order by is_primary desc
        limit 1
       ) as img_id
from prt_gebouw pgb;

如果您想要图片中的其他字段,请在之后加入:

select pgb.*, i.*  -- I'm using `*` for inconvenience; list the columns here
from (select pgb.*,
             (select i.id
              from prt_image i
              where i.object_id = pgb.id and i.kind = 'object'
              order by is_primary desc
              limit 1
             ) as img_id
      from prt_gebouw pgb
     ) pgb left join
     prt_image i
     on pgb.img_id = i.id;