1

I have two tables:

products (id,title,price)
types (id,idProduct,type,additionalPrice).

I want to make a list that shows all the products and their subsequent types in the most efficient way possible, basically something like this:

Product1 (price1)
ProductType1 (+x USD)
ProductType2 (+y USD)

Product2 (price2)
ProductType3 (+w USD)
ProductType4 (+z USD)

etc

One solution I can think of is using GROUP_CONCAT and exploding the results in PHP, but something tells me there's got to be a better way.

4

2 回答 2

0

我建议查询以下值的记录集...

  • Products.ID
  • Products.Title
  • Products.Price
  • Types.Type
  • Types.AdditionalPrice

...然后在获得数据后使用 PHP 来处理格式。如果您对结果进行排序,Products.Title那么Types.Type使用最少的 PHP 编码就可以很容易地获得所需的输出。

查询将如下所示:

SELECT
  Products.ID
  Products.Title
  Products.Price
  Types.Type
  Types.AdditionalPrice
FROM Products
INNER JOIN Types ON Products.ID = Types.idProducts
ORDER BY Products.Title, Types.Type

您甚至可能不需要该Products.ID值,尽管在前端有一个可用的 PK 通常很有用。无论如何,您可以从SELECT列表中省略它(但不是连接!)并且查询会很好。

于 2013-05-17T13:51:44.303 回答
0

我希望这是您正在寻找的 pandronic:

SELECT p.id, p.title, p.price, t.type
FROM products p
INNER JOIN types t ON (t.idProduct = p.id)

如果您想按产品对结果集进行分组,那么您可以这样做

SELECT p.id, p.title, p.price, GROUP_CONCAT(t.type)
FROM products p
INNER JOIN types t ON (t.idProduct = p.id)
GROUP BY p.id
于 2013-05-17T13:46:27.413 回答