Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MySQL中一次从两个表中选择多行_Mysql_Select_Join - Fatal编程技术网

在MySQL中一次从两个表中选择多行

在MySQL中一次从两个表中选择多行,mysql,select,join,Mysql,Select,Join,我有两张桌子: products (id,title,price) types (id,idProduct,type,additionalPrice). 我想列出一个列表,以最有效的方式显示所有产品及其后续类型,基本上如下所示: Product1 (price1) ProductType1 (+x USD) ProductType2 (+y USD) Product2 (price2) ProductType3 (+w USD) ProductType4 (+z USD) etc SEL

我有两张桌子:

products (id,title,price)
types (id,idProduct,type,additionalPrice).
我想列出一个列表,以最有效的方式显示所有产品及其后续类型,基本上如下所示:

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

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

etc
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

我能想到的一个解决方案是使用GROUP_CONCAT并在PHP中分解结果,但有些东西告诉我必须有一个更好的方法。

我希望这就是您正在寻找的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

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

产品编号 产品名称 产品,价格 类型,类型 类型.附加价格 。。。一旦你有了数据,就用PHP来处理格式。如果您按Products.Title和Types.Type对结果进行排序,那么通过最少的PHP编码就可以很容易地获得所需的输出

查询如下所示:

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

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

etc
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通常很有用。无论如何,您可以将其从选择列表中忽略,但不能将其加入!查询会很好。

不,我知道GROUP_CONCAT,但感觉有点不对劲。我实现了这个解决方案,它是最简单的。我希望有更深奥的东西:谢谢你,伙计,事情终于解决了!我也喜欢更复杂的解决方案-也许下次: