MySQL:如何从每个类中获取最多两个图像

时间:2016-04-28 03:03:05

标签: mysql mysql-workbench

我有两张桌子:

(1)for (char character : word) { auto it = UppercaseConvert.find(character); char ch = it == UppercaseConvert.end() ? character : it->second; ConvertedString.push_back( ch ); } (2)class

我想运行一个查询,为明天参加的所有类动态设置变量,然后按字母顺序显示该类成员的前2个缺失图像。

e.g。像这样的东西:

images

我希望能给我一些类似的东西:

SET @class = (
    SELECT
        id
    FROM
        class
    WHERE
        attending > CURDATE()
    AND attending < CURDATE() + INTERVAL 2 DAY
);

SELECT
    class_id,
    NAME
FROM
    images
WHERE
    class_id = @class
AND image_path IS NULL
ORDER BY
    NAME ASC
LIMIT 2;

1 个答案:

答案 0 :(得分:1)

基本上这两个表(类和图像)之间的INNER JOIN可以完成任务:

SELECT 
images.class_id,
images.NAME
FROM class 
INNER JOIN images ON class.id = images.class_id
WHERE class.attending > CURDATE() AND class.attending < CURDATE() + INTERVAL 2 DAY
AND images.image_path IS NULL
ORDER BY images.NAME
LIMIT 2;

修改

SELECT 
t.class_id,
t.name
FROM 
(
    SELECT 
        images.class_id,
        images.NAME,
        IF(@prevClassId = images.class_id, @classPosition := @classPosition + 1 , @classPosition := 0) rank,
        @prevClassId := images.class_id
    FROM (SELECT @prevClassId := NULL, @classPosition := 0) vars,class 
    INNER JOIN images ON class.id = images.class_id
    WHERE class.attending > CURDATE() AND class.attending < CURDATE() + INTERVAL 2 DAY
    AND images.image_path IS NULL
    ORDER BY images.class_id
) t
WHERE t.rank < 2;

SQL FIDDLE DEMO

样本数据(班级表):

id  class_name  attending

1   one         4/29/2016
4   Four        4/29/2016
8   Eight       4/29/2016
13  Thirteen    4/29/2016

样本数据(图像表):

id  class_id  name      image_path
1     1       IMG_ONE   IMAGE ONE PATH
2     4       Anna      (NULL)
3     4       Bjorn     (NULL)
4     4       C4        (NULL)
5     8       Alex      (NULL)
6     8       Ceri      (NULL)

<强>输出:

class_id    NAME
4           Bjorn
4           Anna
8           Ceri
8           Alex