【问题标题】:Mysql where if conditionmysql where if 条件
【发布时间】:2019-11-22 08:08:29
【问题描述】:

基本上我有一个表,所有客户都会有一个默认行customer_group_id=0

但是这个客户中的一些将属于customer_group_id=1

当发生这种情况时,会为 customer_group_id=1 的客户创建一个新行,因此现在我有 2 行用于同一客户但不同的 customer_group_id。

现在,当我获取数据时,我首先需要从 customer_group_id =1 的客户表中选择 *,但如果不存在,则给我,然后使用 customer_group_id = 0 这是默认值,并继续直到它返回所有数据。

有人知道实现这一速度的最佳方法吗?

更新:屏幕截图显示 2 行具有相同 customer_id 不同 customer_group_id

我需要一个或另一个,所以层次结构是:如果 customer_group_id=1 存在则返回该行并忽略其他,否则返回默认值 customer_group_id=0

我的完整查询:

SELECT `main_table`.*, `secondTable`.* FROM `customer` AS `main_table` 
LEFT JOIN `customer_group` AS `secondTable` ON main_table.customer_id = secondTable.customer_id 
WHERE (secondTable.customer_group_id = '1' ) 
AND (`secondTable`.`is_active` = '1')

【问题讨论】:

  • 如果您想获取所有客户,为什么不只使用 select * from;并使用“distinct”子句避免重复?
  • 听起来架构需要规范化。虽然你的问题缺乏细节。无论如何,您可以尝试以下方法:SELECT * FROM your_table_name WHERE customer_id = $customer_id ORDER BY customer_group_id DESC LIMIT 1

标签: mysql sql if-statement conditional-statements


【解决方案1】:

如果你只有两个组,那么聚合很简单:

select customer_id, max(customer_group_id)
from t
group by customer_id;

在 MySQL 8+ 中,您可以使用 row_number() 实现更高的客户优先级:

select t.*
from (select t.*,
             row_number() over (partition by customer_id order by customer_group_id desc) as seqnum
      from t
     ) t
where seqnum = 1;

【讨论】:

  • 第一个解决方案对我有用,它只返回一个或另一个。我会尝试第二个,但获取数据似乎更耗时。
  • 还有一件事如果有更多的组,如 2,3 和 4,但只为其中一个或 0 获取它们,否则 0 仍然有效吗?
  • @JulianoVargas 。 . .如果您只关心两组,您可以将where customer_group_id in (0, 4) 添加到任一查询中。这是有效的,因为所有客户都有0
  • 整个查询对我来说不太有效,因为我需要做的是选择所有内容并 LEFT JOIN 到另一个表和 Where second_table.customer_id=1 如果我使用 in(0,2) 或in(0,4) 它返回重复项。
  • @JulianoVargas 。 . . group bywhere seqnum = 1 删除重复项。
【解决方案2】:

您可以做的是使用customer_group_id=1 获取客户的所有行,然后使用UNION ALL 通过使用NOT EXISTS 获取没有任何customer_group_id=1 行的客户的行:

select * from tablename
where customer_group_id=1
union all
select * from tablename t
where t.customer_group_id=0
and not exists (
  select 1 from tablename
  where customer_id = t.customer_id and customer_group_id=1
)

【讨论】:

    【解决方案3】:

    对于带有customer_group_id = 0 的行,请验证对于相同的customer_id,没有带有customer_group_id = 1 的行。您可以使用 NOT EXISTS 子查询:

    SELECT c.*, g.*
    FROM customer AS c
    JOIN customer_group AS g ON c.customer_id = g.customer_id 
    WHERE NOT EXISTS (
        SELECT *
        FROM customer_group AS g2
        WHERE g2.customer_id = c.customer_id
          AND g2.customer_group_id = 1
          AND g.customer_group_id  = 0
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多