我可以只用SQL做到这一点吗? [英] Can I do this with just SQL?

查看:74
本文介绍了我可以只用SQL做到这一点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有两个表,产品选项

产品包含


  1. id

  2. title

  3. 说明

选项包含


  1. id

  2. product_id

  3. sku

  4. title

  1. id
  2. product_id
  3. sku
  4. title

示例数据可能是:

产品

id:1

标题:'test'

描述:'我的描述'

Products
id: 1
title: 'test'
description: 'my description'

选项

id:1

product_id:1

sku:1001

标题:红色'

Options
id: 1
product_id: 1
sku: 1001
title: 'red'

id:2

product_id:1

sku:1002

标题:'蓝色'

id: 2
product_id: 1
sku: 1002
title: 'blue'

我需要显示每个项目以及每个不同的选项。此刻,我在 products 中选择行,并对其进行迭代,然后为每个行从 options 。然后,我创建一个数组,类似于:

I need to display each item, with each different option. At the moment, I select the rows in products and iterate through them, and for each one select the appropriate rows from options. I then create an array, similar to:

[product_title] = 'test';  
[description]   = 'my description';  
[options][]     = 1, 1001, 'red';  
[options][]     = 2, 1002, 'blue';

是否有更好的方法仅使用sql(我正在使用codeigniter,并且理想情况下喜欢使用Active Record类)?

Is there a better way to do this with just sql (I'm using codeigniter, and would ideally like to use the Active Record class)?

推荐答案

SELECT * FROM products INNER JOIN options ON product.id = options.product_id

并从那里开始工作。

该示例仅适用于具有至少一个可用选项的产品(这是您的设计所必需的,否则您无处可放) SKU)。但是,如果某些产品根本没有任何选择,那么您需要:

The example only works for products with at least one option available (which is required by your design, otherwise you have no place for the SKU). But if some products don't have any options at all, you want:

SELECT * FROM products LEFT JOIN options ON product.id = options.product_id

最后,列出要返回的实际列被认为是一种好习惯而不是SELECT *。

Finally, it's considered good practice to list the actual columns you want to get back instead of SELECT *.

这篇关于我可以只用SQL做到这一点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆