gpt4 book ai didi

mysql - 如何根据字段的值选择不同的列

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:36 25 4
gpt4 key购买 nike

我有两个表 productsdimensionsdimensions 表包含以下字段:product_id、name、value、unit。

我想联接这些表,以便每个维度名称在结果中显示为单独的列。例如。我在尺寸表中有以下条目:

1, width, 4, inches
2, width, 5, inches
1, length, 10, inches
2, height, 7, inches

我希望结果是这样的:

product id, length, length unit, width, width unit, height, height unit
1 10 inches 4 inches
2 5 inches 7 inches

我如何使用 sql 查询实现此目的?

最佳答案

您可以尝试将其用于 LEFT JOIN 语句。

例如

SELECT p.id, l.value AS length, l.unit AS length_unit, w.value AS width, w.unit AS width_unit, h.value AS height, h.unit AS height_unit
FROM products AS p
LEFT JOIN dimensions AS l ON (p.id = l.product_id AND l.name = 'length')
LEFT JOIN dimensions AS w ON (p.id = w.product_id AND w.name = 'width')
LEFT JOIN dimensions AS h ON (p.id = h.product_id AND h.name = 'height')

关于mysql - 如何根据字段的值选择不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26795464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com