MySQL选择存在其他3行的行

时间:2014-10-01 22:31:57

标签: mysql sql

有2个表

实体

+----+---------+
| id | name    |
+----+---------+
| 4  | store_1 |
+----+---------+

公布

+----+-------------+
| id | status      |
+----+-------------+
| 4  | sold        |
| 4  | bought      |
| 4  | transferred |
| 4  | sold        |
| 4  | transferred |
+----+-------------+

我目前正在尝试从entities中选择所有条目,其中"已销售","已购买","已转移"在published表格中至少存在一次。

使用左连接只会将行推送到已发布表中存在的每一行的结果,因为实体可能具有重复的已发布状态。

所以,这就是我提出的,它的工作......

select
    entities.id,
    (
        select count(distinct `status`)
        from published
        where id = entities.id
            and `status` in ('sold', 'bought', 'transferred')
    ) as statusCount
from entities
having statusCount = 3;

这感觉有点笨重。有更好的方法吗?

4 个答案:

答案 0 :(得分:2)

SELECT e.ID
FROM  entities e INNER JOIN published P
ON e.id = P.id
GROUP BY e.ID
HAVING COUNT(DISTINCT Status) >= 3

答案 1 :(得分:2)

是的,上面的答案是正确的。除非你有其他状态,除了这里提到的三个。您可以使用where子句对其进行过滤。

SELECT e.Id
FROM entities e INNER JOIN published P
ON e.Id = P.Id
WHERE status in ('sold','bought','transferred')
GROUP BY e.Id
HAVING COUNT(DISTINCT Status) >= 3

答案 2 :(得分:0)

Kartik和M. Ali都直接回答了您的问题 - 但是您是否想过构建您的实体表以获得每个州的标志?那会大大搞清楚。

答案 3 :(得分:0)

-- If we need the entity where 'bought', 'sold' and 'transferred' all appear atleast once
SELECT DISTINCT e.id, e.name
FROM  #published p
    LEFT OUTER JOIN #entity e ON e.id = p.id
GROUP BY p.id, e.id, e.name
HAVING COUNT(CASE p.status WHEN 'sold' THEN 1 ELSE NULL end) > 0
    AND COUNT(CASE p.status WHEN 'bought' THEN 1 ELSE NULL end ) > 0
    AND COUNT(CASE p.status WHEN 'transferred' THEN 1 ELSE NULL end) > 0

-- If we need the entity where either 'bought', 'sold' or 'transferred' appears atleast once
SELECT DISTINCT e.id, e.name
FROM  #published p
    LEFT OUTER JOIN #entity e ON e.id = p.id
GROUP BY p.id, e.id, e.name
HAVING COUNT(CASE WHEN p.status IN ('sold', 'bought', 'transferred') THEN 1 ELSE NULL end) > 0