You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

购物清单外键场景:如何按Aisle ID排序但仅返回标签?

解决方案

纯SQL实现

直接通过JOIN关联两张表,按Aisle表的id字段排序,仅返回aislelabel字段即可。如果需要避免重复的 aisle 标签,可以加上DISTINCT关键字:

-- 去重版本,避免重复的aislelabel
SELECT DISTINCT a.aislelabel
FROM Ingredients i
JOIN Aisle a ON i.aisle = a.id
ORDER BY a.id;

-- 不去重版本,保留所有关联的aislelabel(适合需要统计每个食材对应 aisle 的场景)
SELECT a.aislelabel
FROM Ingredients i
JOIN Aisle a ON i.aisle = a.id
ORDER BY a.id;

Python中结合数据库库实现

1. 使用sqlite3(内置库)

如果用Python内置的sqlite3操作数据库,代码示例如下:

import sqlite3

# 连接数据库
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()

# 执行查询
cursor.execute("""
    SELECT DISTINCT a.aislelabel
    FROM Ingredients i
    JOIN Aisle a ON i.aisle = a.id
    ORDER BY a.id
""")

# 获取结果
results = cursor.fetchall()
# 转换为列表格式(可选)
aisle_labels = [row[0] for row in results]

# 关闭连接
conn.close()

2. 使用SQLAlchemy(ORM框架)

如果用ORM来简化操作,代码示例如下:

首先定义模型:

from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()

class Aisle(Base):
    __tablename__ = 'Aisle'
    id = Column(Integer, primary_key=True)
    aislelabel = Column(String)
    ingredients = relationship("Ingredients", back_populates="aisle")

class Ingredients(Base):
    __tablename__ = 'Ingredients'
    id = Column(Integer, primary_key=True)
    food_desc = Column(String)
    protein = Column(Float)
    carbs = Column(Float)
    fat = Column(Float)
    price = Column(Float)
    aisle_id = Column(Integer, ForeignKey('Aisle.id'))
    aisle = relationship("Aisle", back_populates="ingredients")

# 连接数据库
engine = create_engine('sqlite:///your_database.db')
Session = sessionmaker(bind=engine)
session = Session()

# 查询并排序
aisle_labels = session.query(Aisle.aislelabel)\
                      .join(Ingredients)\
                      .distinct()\
                      .order_by(Aisle.id)\
                      .all()

# 转换为列表
aisle_labels = [label[0] for label in aisle_labels]

session.close()

内容的提问来源于stack exchange,提问作者mikeyv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:10:32