从不同的内部联接表中选择值

时间:2014-05-20 00:06:18

标签: mysql sql

我有以下查询:

SELECT picture.id
FROM app_instagram_picture_category category
INNER JOIN app_instagram_shop_picture picture ON category.picture_id = picture.id
INNER JOIN app_instagram_shop shop ON shop.id = picture.shop_id
WHERE category.first_level_category_id =10
AND shop.isLocked =0
AND shop.expirydate IS NOT NULL 
AND shop.expirydate >  '2014-05-20'
AND shop.owner_id IS NOT NULL 
LIMIT 0, 10;

我想得到10个独特的picture.id,每个来自不同/不同的商店,我该怎么做?我应该使用GROUP BY吗?如果是的话怎么样?

为了澄清这个问题,让我这样说吧:

说我有10家商店,A,B,C,D,E,F,G,H,I,J。我想从这些商店中得到1张图片,所以总共10张图片,每张图片属于一个不同的商店

2 个答案:

答案 0 :(得分:0)

shop.id和picture.id之间有什么关系?看起来一个商店行可以链接到许多图片行。如果是这样,就没有直接的说法"对于每个商店,只选择一张图片。"从逻辑上考虑一下:声明如何在同一商店的不同图片之间做出决定?它是随意的吗?

我必须建立一个声明(报告),我想从一对多的关系中选择一行,而且我选择哪一行并不重要,所以我做了通过在可用结果中选择max主键

SELECT picture.id, shop.id
FROM app_instagram_shop shop
INNER JOIN (select * from app_instagram_shop_picture p where p.id = 
          (select max(p.id) from app_instagram_shop_picture subp where p.shop_id = subp.shop_id)
    ) picture ON (shop.id = picture.shop_id)
INNER JOIN app_instagram_picture_category category ON (category.picture_id = picture.id)
WHERE category.first_level_category_id =10
AND shop.isLocked =0
AND shop.expirydate IS NOT NULL 
AND shop.expirydate >  '2014-05-20'
AND shop.owner_id IS NOT NULL

如果我对你要做的事情或你的桌子之间的关系错了,请纠正我。

编辑:我看到你想要做的更多。试试这个:

SELECT picture.id, shop.id
FROM app_instagram_shop shop
INNER JOIN (
        select * from app_instagram_shop_picture p LIMIT 0,10
    ) picture ON (shop.id = picture.shop_id)
INNER JOIN app_instagram_picture_category category ON (category.picture_id = picture.id)
WHERE category.first_level_category_id =10
AND shop.isLocked =0
AND shop.expirydate IS NOT NULL 
AND shop.expirydate >  '2014-05-20'
AND shop.owner_id IS NOT NULL

答案 1 :(得分:0)

    SELECT 
        picture.id
    FROM 
        app_instagram_picture_category category
        INNER JOIN app_instagram_shop_picture picture ON category.picture_id = picture.id
        INNER JOIN app_instagram_shop shop ON shop.id = picture.shop_id
    WHERE 
        category.first_level_category_id =10
        AND shop.isLocked =0
        AND shop.expirydate IS NOT NULL 
        AND shop.expirydate >  '2014-05-20'
        AND shop.owner_id IS NOT NULL 
    GROUP BY 
        shop.id