JOIN WHERE右表没有条目

问题描述 投票:-1回答:1

我有3个表产品,版本和货币。

是否可以查询具有MAX版本但尚未拥有任何货币的产品,其中货币版本_id = MAX版本的ID?

编辑

要求提供示例数据。

产品表

id      name
1       product a
2       product b
3       product c
4       product d

版本表

id      product_id     version_no
1       1              1
2       2              1
3       2              2
4       3              1
5       3              2
6       4              1

货币表

id      product_id     version_id   currency
1       1              1            USD
2       2              2            USD
3       2              3            USD
4       3              4            USD

从这些数据,我应该得到这个:

product_id      product_name
3               product c
4               product d

这是因为在以下产品的Max版本上

product_id      version
1               1
2               2
3               2
4               1

只有产品3和4在这些version_nos的货币表上没有条目

这够清楚了吗?

mysql
1个回答
1
投票

使用左连接:并且具有空值的where条件将为您提供所需的结果

select product_id,name
    from
    (select product_id, max(version_id) as vid
    from versiontable 
    group by product_id) v
    left join currencytable c on v.product_id=c.product_id and v.vid=c.version_id
    left join procuttable p on p.id=v.product_id
    where c.product_id is null and c.version_id is null
© www.soinside.com 2019 - 2024. All rights reserved.