【问题标题】:Sql query to derive a column value based on the entry in another tableSql查询根据另一个表中的条目派生列值
【发布时间】:2012-09-04 10:31:48
【问题描述】:

我有一个 person 表,其中包含 idemail 字段。

还有一个 subscription 表,其中包含以下字段:person_idcategory_id

如果有人订阅了订阅表,表中将至少有一个条目。

我想查询 person 表,其中第 3 列有 1 或 0,具体取决于 person 是否订阅。

select p.id, p.email , [is_subscribed] 
from person p
如果 subscription 表中有条目,

is_subscribed 应为 1,否则应为 0。

我怎样才能达到上述目的?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    在订阅和计数上使用 LEFT JOIN(在多个订阅的情况下)

    SELECT p.id,p.email,IF(COUNT(s.category_id)>0,1,0) as is_subscribed
    FROM
    person as p
    LEFT JOIN subscription as s ON s.person_id=p.id
    GROUP BY p.id
    

    【讨论】:

    • 感谢您的快速解决方案 :)
    【解决方案2】:
    SELECT p.`id` , p.`email` , IF(COUNT(s.`id`)>0,1,0) AS count
    FROM  `person` p
    LEFT JOIN  `subscription` s ON s.`person_id` = p.`id` 
    

    【讨论】:

      【解决方案3】:
         select distinct p.id, p.email, ifnull(sign(subscription.id),0) as is_subscribed
         from
             person
                 left join subscriptions
                 on person.id = subscriptions.person_id
      

      【讨论】:

        【解决方案4】:

        select distinct person.id, person.email, cast((select count(id) from sub where id=1) as bit) from tab, sub where tab.id=1;

        这是一个 MS SQL 服务器查询。对 mysql 进行必要的更改。

        【讨论】:

          猜你喜欢
          • 2020-04-07
          • 2018-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-13
          • 1970-01-01
          • 2022-08-17
          相关资源
          最近更新 更多