MySQL - 条件选择

发布于 2024-09-19 16:35:17 字数 302 浏览 0 评论 0原文

我有表 itemstore (它是一个商店管理系统)。 item 表有一个名为 store_id 的列和另一个名为 status 的列。 item.status 可以是“已售出”或“未售出”。

我需要帮助编写一个查询来执行以下操作:

  • 如果商店只有一件商品并且该商品已“售出”,则选择所有商店的所有商品
  • ,从结果集中删除该商品

提前致谢!

I have tables item and store (it's a store management system). item table has a column called store_id and another column called status. item.status can be 'sold' or 'unsold'.

I need help writing a query which will do these things:

  • select all items of all stores
  • if a store has just one item and that item is 'sold', remove that item from the result set

Thanks in advance!

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

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

发布评论

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

评论(1

晚雾 2024-09-26 16:35:31

您可以创建一个过滤子查询来搜索拥有多于一件商品或一件未售出商品的商店。然后您可以在原始表上加入子查询,例如:

select  *
from    (
        select  s2.store_id
        from    store s2
        join    items i2
        on      s2.store_id = i2.store_id
        group by
                s2.store_id
        having 
                count(*) > 1 -- More than one item
                or max(i2.status) = 'unsold' -- One item but unsold
        ) filter
join    store s
on      filter.store_id = s.store_id
join    items i
on      s.store_id = i.store_id

You could create a filtering subquery that searches for stores with more than one item, or one unsold item. Then you can join the subquery on the original tables, like:

select  *
from    (
        select  s2.store_id
        from    store s2
        join    items i2
        on      s2.store_id = i2.store_id
        group by
                s2.store_id
        having 
                count(*) > 1 -- More than one item
                or max(i2.status) = 'unsold' -- One item but unsold
        ) filter
join    store s
on      filter.store_id = s.store_id
join    items i
on      s.store_id = i.store_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文