我有了这种结构的表格:回报是,如果只有一条记录被发现
table
id | site_id
-------------------
240 | 1
240 | 2
240 | 3
320 | 1
320 | 2
421 | 1
520 | 2
-------------------
300K记录
我现在想编写一个查询返回一个是或否的每个记录(id)。
例如,如果与ID记录240 只有有SITE_ID 1然后返回“是”,如果它有2个,3等回报“否”
我不知道如何处理它但这里是一个结果示例:
result_table
.-----------------------.
| id | result |
|-----------------------|
| 240 | No | -- has a site_id 1, 2 and 3
| 320 | No | -- has a site_id 1 and 2
| 421 | Yes | -- has a site_id 1 only
| 520 | No | -- has a site_id 2
'-----------------------'
下面是该查询我到目前为止,但它似乎是不正确的
SELECT CASE WHEN count(id) > 1 THEN 'N' ELSE 'Y' END as Result
FROM table sm
WHERE sm.site_id IN (1)
AND sm.site_id NOT IN (2,3,4,5,6,7,8,9)
AND id = 240
UPDATE
所以这里是我完整的查询,我从@gordon
SELECT
m.merchant_name,
m.merchant_id,
ut.realname,
a.affiliate_name,
(select (case when count(site_id) = 1 then 'Yes' else 'No' end) as result
from site_merchant sm
WHERE sm.merchant_id = m.merchant_id
group by merchant_id) as isTjoos, -- y or no
(select (case when count(site_id) = 2 then 'Yes' else 'No' end) as result
from site_merchant sm
WHERE sm.merchant_id = m.merchant_id
group by merchant_id) as isUCOnly
-- isdlkonly -- y or no
FROM merchant m
LEFT JOIN merchant_editor_assignment mea ON mea.merchant_id = m.merchant_id
LEFT JOIN user_table ut ON ut.user_id = mea.user_id
LEFT JOIN affiliate a ON a.affiliate_id = m.affiliate_id_default
@lbu。 。 。有多种方式来解释你的问题。你能详细说明吗?特别是,您是否正在寻找具有site_id = 1的1行的id?你在寻找只有site_id = 1的行吗?或者,你在寻找所有行都有相同site_id的id吗? – 2013-02-25 20:20:51
这是一个子查询,我将寻找其他记录,将有site_id 2,只有2和3,只有3; – Ibu 2013-02-25 20:22:21
@Ibu:看看我的答案:SUM是site_id。 – shahkalpesh 2013-02-25 20:26:12