简体   繁体   English

SQL查询基于另一个表中的条目派生列值

[英]Sql query to derive a column value based on the entry in another table

I have a person table with fields id , email . 我有一个表,包含字段idemail

And a subscription table with fields: person_id , category_id . 以及具有以下字段的订阅表: person_idcategory_id

If a person is subscribed subscription table will have at-least one entry in the table. 如果一个人被订阅,则订阅表将在该表中至少有一个条目。

I want to query person table with the 3rd column having 1 or 0 depending on whether person is subscribed or not. 我想查询人员表,其第三列的值为1或0,具体取决于人员是否已订阅。

select p.id, p.email , [is_subscribed] 
from person p

is_subscribed should be 1 if there is an entry in the subscription table else should be 0. 如果订阅表中有一个条目,则is_subscribed应该为1,否则应为0。

How can I achieve the above ? 如何实现以上目标?

Using a LEFT JOIN on subscription & a count (in a case of several subscriptions) 在订阅和计数上使用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
   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
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` 

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

This is an MS SQL server query. 这是一个MS SQL服务器查询。 Make necessary changes for mysql. 对mysql进行必要的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM