在 PostgreSQL 中连接具有两个条件或两列共有的表

发布于 2025-01-15 15:57:57 字数 2372 浏览 0 评论 0原文

我有两张桌子。表 1 列出了商店中所有商品的商品、颜色和尺寸。表 2 是定价列表,包含商品、尺寸、价格和商品 ID。价格由商品和尺寸决定。如何将价格显示在表 1 上?

表 1-

商品颜色尺码
示例衬衫红色M
裤子蓝色S

...

表 2-

商品尺码价格示例item_size_id
衬衫S2.99013443
衬衫M3.99013444
衬衫L4.99013445
裤子S5.99013452

...

想要的结果:

商品颜色尺码价格
衬衫红色M3.99
裤子蓝色S5.99

...

我尝试过:

SELECT item, color, size, price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size

但这导致所有价格为空。

我已经尝试过 CASE WHEN 语句,虽然这有效,但花了很长时间,所以有更好的方法吗?

I have two tables. Table 1 has item, color, and size for all items in the store. Table 2 is a pricing list and has item, size, price, and itemid. Price is determined from item and size. How can I get the price on to Table 1?

Table1- Example

itemcolorsize
shirtredM
pantsblueS

...

Table2- Example

itemsizepriceitem_size_id
shirtS2.99013443
shirtM3.99013444
shirtL4.99013445
pantsS5.99013452

...

Result wanted:

itemcolorsizeprice
shirtredM3.99
pantsblueS5.99

...

I have tried:

SELECT item, color, size, price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size

But this results in all nulls for price.

I have tried CASE WHEN statements and while this worked, it took forever so is there is a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚笙 2025-01-22 15:57:57

您的查询是正确的,只是两个表中都存在同名的列,并且您没有指定所引用的列。
有关架构和测试,请参阅下面的 dbFiddle 行。

 /* query provided in the question as provided */
SELECT item, color, size, price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size
ERROR:  column reference "item" is ambiguous
LINE 2: SELECT item, color, size, price
               ^
/* query provided with table identifiers added */
SELECT table1.item, table1.color, table1.size, table2.price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size
item  | color | size | price
:---- | :---- | :--- | ----:
pants | blue  | S    |  5.99
shirt | red   | M    |  3.99

db<>fiddle 此处

Your query is correct, except that columns of the same name exist in both tables and you have not specified which one you are referring to.
See dbFiddle line below for schema and testing.

 /* query provided in the question as provided */
SELECT item, color, size, price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size
ERROR:  column reference "item" is ambiguous
LINE 2: SELECT item, color, size, price
               ^
/* query provided with table identifiers added */
SELECT table1.item, table1.color, table1.size, table2.price
FROM table1
LEFT JOIN table2
ON table1.item = table2.item AND table1.size = table2.size
item  | color | size | price
:---- | :---- | :--- | ----:
pants | blue  | S    |  5.99
shirt | red   | M    |  3.99

db<>fiddle here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文