如果满足条件,如何替换答案

时间:2017-09-15 04:05:53

标签: mysql

我正在研究如何在满足条件时编写一个替换答案的sql查询。在这种情况下,我们的成员可以对“您希望其他成员查看您的电子邮件地址吗?”这一问题拒绝。以下查询列出了所有成员及其电子邮件地址以及问题的答案,我需要替换那些拒绝的人的电子邮件地址,并附上“不适用于出版物或类似”的信息。

select josvy_osmembership_subscribers.`id`as ID,
    concat (`first_name`," ",`last_name`) as name,
    josvy_osmembership_field_value.`field_value` as Answer,
    `email`AS Email,
    `plan_id`AS plan,
    `plan_subscription_status` as status,
    josvy_osmembership_field_value.field_id as Field_id
from `josvy_osmembership_subscribers`,
    `josvy_osmembership_field_value`
where josvy_osmembership_subscribers.id = josvy_osmembership_field_value.Subscriber_Id
    and plan_id = 1
    and plan_subscription_status = 1
    and josvy_osmembership_field_value.`field_id` = 16
order by ID

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询隐藏回复为No

的成员的电子邮件地址
SELECT 
  s.`id` AS ID,
  CONCAT(`first_name`, " ", `last_name`) AS NAME,
  v.`field_value` AS Answer,
  CASE
    WHEN v.`field_value` = 'No' 
    THEN 'Not For Publication or similar'
    ELSE `email` 
  END AS Email,
  `plan_id` AS Plan,
  `plan_subscription_status` AS STATUS,
  v.field_id AS Field_id 
FROM
  `josvy_osmembership_subscribers` s
  JOIN `josvy_osmembership_field_value` v 
    ON s.id = v.Subscriber_Id 
WHERE plan_id = 1 
  AND plan_subscription_status = 1 
  AND v.`field_id` = 16 
ORDER BY ID 

答案 1 :(得分:0)

您可以使用CASE表达式根据答案的值有条件地选择电子邮件或消息

select s.id as id,
    concat (first_name, ' ', last_name) as name,
    v.field_value as answer,
    case when v.field_value = 'No' then 'Not For Publication or similar' else email end as email,
    plan_id as plan,
    plan_subscription_status as status,
    v.field_id as field_id
from josvy_osmembership_subscribers s
join josvy_osmembership_field_value v on s.id = v.subscriber_id
where plan_id = 1
    and plan_subscription_status = 1
    and v.field_id = 16
order by id

此外,始终使用显式连接语法而不是旧的基于逗号的连接,并尝试使用别名来清理查询,而不是在任何地方使用整个表名。