【问题标题】:Querying 3 tables by comparing column values and with no primary or foreign key relationship比较列值查询3张表,无主外键关系
【发布时间】:2016-03-31 05:53:16
【问题描述】:

我有 3 张桌子 A、B 和 C。 表 A 包含产品详细信息,其中没有价格列。 表 B 和 C 包含产品详细信息,其中包含价格列。

表 A 中的产品可能出现在表 B 或 C 中,也可能不出现。

如果表 B 或 C 中存在表 A 的产品,我想获取该产品的最低价格,并从 B 或 C 中选择最低价格

假设表 A 具有 Property1 、 Property2 和 Property3


表 B 有 Price、Property1、Property2 和 Property3


表 C 有 Price、Property1、Property2 和 Property3

从表 B 或 C 中获取产品的最低价格,以 A.properties 与 B 和 C 的属性匹配的价格为准

如何查询。

【问题讨论】:

  • 发布示例数据对所有人都有帮助
  • mysql 还是 sql-server?

标签: mysql sql sql-server database join


【解决方案1】:

试试这个:

SELECT big.prop1, big.prop2, MIN(big.price)
FROM (
    SELECT a.prop1, a.prop2, b.price
    FROM TableA a
    INNER JOIN TableB b ON a.prop1 = b.prop1 AND a.prop2 = b.prop2

    UNION

    SELECT a.prop1, a.prop2, c.price
    FROM TableA a
    INNER JOIN TableC c ON a.prop1 = c.prop1 AND a.prop2 = c.prop2
) AS Big
GROUP BY big.prop1, big.prop2

但是,这是一种不好的做法,您需要每个组合 og 属性的外键来连接表。

【讨论】:

  • 这将返回来自 a 的记录,即使它们不存在于 b 或 c 中。请参阅下面的解决方案,如果 a 或 b 中都不存在,则不会从 a 返回记录。
  • @JoshGilfillan-谢谢,如果我可以在这里放置类似的条件,我想再检查一件事。因为 a.property1 是“Samsung Mobile”,而 c.prop1 是“Samsung”,所以有没有办法可以在这里点个赞。 a.prop1 和 c.prop1 一样。
  • @John 你可以把它放在GROUP BY 之前或在aech INNER JOIN 之后添加WHERE
【解决方案2】:

您可以将表 b 和 c 中的数据与 union all 组合,然后使用 inner join 到表 a,再结合 min()group by 以获得最低价格。

select a.property1, a.property2, a.property3, min(x.price) as min_price
from table_a a

-- join to combined data from table b and table c
inner join (
  select price, property1, property2, property3
  from table_b 
  union all
  select price, property1, property2, property3
  from table_c
) x
-- join on properties
on a.property1= x.property1
and a.property2= x.property2
and a.property3= x.property3
)
group by a.property1, a.property2, a.property3

【讨论】:

    【解决方案3】:
    create table #a (Property varchar(10))
    INSERT INTO #A VALUES ('X')
    INSERT INTO #A VALUES ('D')
    INSERT INTO #A VALUES ('I')
    
    create table #b (price int,Property varchar(10))
    INSERT INTO #B VALUES (10,'X')
    INSERT INTO #B VALUES (11,'D')
    INSERT INTO #B VALUES (12,'I')
    
    create table #c (price int ,Property varchar(10))
    
    INSERT INTO #C VALUES (8,'X')
    INSERT INTO #C VALUES (9,'D')
    INSERT INTO #C VALUES (7,'I')
    
    SELECT B.PROPERTY,CASE WHEN MIN(B.PRICE) <  MIN (C.PRICE) THEN B.PRICE ELSE C.PRICE END AS PRICE
    FROM #B B INNER JOIN #C C ON B.Property=C.Property INNER JOIN #A A ON B.Property=A.Property
    GROUP BY B.PRICE,C.PRICE,B.PROPERTY
    
    DROP TABLE #A
    DROP TABLE #B
    DROP TABLE #C
    

    【讨论】:

    • 复制粘贴此查询并在sql中执行以了解输出。
    猜你喜欢
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多