2

实体:

class Car(db.Entity):
    image = Set("Image")
    name = Required(str, 40,)

class Image(db.Entity):
    name = Required(str, unique=True)
    car = Required(Car)

我想在汽车列表页面上获取信息:一辆车 - 那辆车的一张图片。

我用:

cars = select((car, car.image) for car in Car).distinct().show()

我有

Car[1]|Image[1]  
Car[1]|Image[2]  
...
Car[5]Image[1]
Car[5]Image[2]
...

但我只需要每辆车的第一张图像,而不是所有图像。

这个怎么做?

谢谢!

4

1 回答 1

4

仅获取每辆车的第一张图像的代码(具有最低 id 的图像):

#!/usr/bin/env python
from pony.orm import *

db = Database()
db.bind('sqlite', ':memory:', create_db=True)


class Car(db.Entity):
    image = Set("Image", lazy=True)
    name = Required(str, 40)

class Image(db.Entity):
    name = Required(str, unique=True)
    car = Required(Car)    

db.generate_mapping(create_tables=True)

sql_debug(True)

with db_session:
    car1 = Car(name='car1')
    car2 = Car(name='car2')
    image1 = Image(name='image1', car = car1)
    image2 = Image(name='image2', car = car1)
    image3 = Image(name='image3', car = car2)
    cars = select((car, car.name, image, image.name) for car in Car for image in car.image if image.id == min(car.image.id)).show()

结果:

GET CONNECTION FROM THE LOCAL POOL
SWITCH TO AUTOCOMMIT MODE
BEGIN IMMEDIATE TRANSACTION
INSERT INTO "Car" ("name") VALUES (?)
[u'car1']

INSERT INTO "Car" ("name") VALUES (?)
[u'car2']

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image1', 1]

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image2', 1]

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image3', 2]

SELECT "car"."id", "car"."name", "image"."id", "image"."name"
FROM "Car" "car"
  LEFT JOIN "Image" "image-1"
    ON "car"."id" = "image-1"."car"
  LEFT JOIN "Image" "image"
    ON "car"."id" = "image"."car"
GROUP BY "car"."id", "car"."name", "image"."id", "image"."name"
HAVING "image"."id" = MIN("image-1"."id")

car   |car.name|image   |image.name
------+--------+--------+----------
Car[1]|car1    |Image[1]|image1    
Car[2]|car2    |Image[3]|image3    
COMMIT
RELEASE CONNECTION

顺便说一句,生成的 sql 比较奇怪,我认为执行两个相同的左连接没有任何意义。编辑:好的,这是有道理的(见评论)。

于 2015-05-30T21:09:11.360 回答