[英]Select rows that has one value but not another from same table
I have a table like below in MySQL.我在 MySQL 中有一张如下表。 I want all the rows that have name A but not name B.我想要所有名称为 A 但不是名称 B 的行。
I want a result like this.我想要这样的结果。 Thank you for helping.感谢您的帮助。
I have tried the following query.我尝试了以下查询。 It is not working.它不工作。
Select fk_id from TableA
where name not like 'B'
group by fk_id
having name like 'A'
Your question isn't particularly clear but it sounds like you want fk_id
having an associated name
value of A
and where any record with the same fk_id
and name
of B
does not exist.您的问题不是特别清楚,但听起来您希望fk_id
具有关联的name
值A
并且不存在具有相同fk_id
和name
B
的任何记录。
Try this尝试这个
SELECT fk_id FROM TableA a
WHERE a.name = 'A'
AND NOT EXISTS (
SELECT 1 FROM TableA b
WHERE b.name = 'B'
AND a.fk_id = b.fk_id
)
Demo ~ http://sqlfiddle.com/#!9/ba0df2/2演示 ~ http://sqlfiddle.com/#!9/ba0df2/2
WITH b_rows AS(
SELECT fk_id AS fk_id_b,
'1' AS flg_b
FROM TableA
WHERE name = 'B'
)
SELECT fk_id
FROM TableA
LEFT JOIN b_rows ON TableA.fk_id = b_rows.fk_id_b
WHERE name = 'A'
AND flg_b <> '1'
How about using GROUP_CONCAT()
in HAVING
like:在HAVING
中使用GROUP_CONCAT()
怎么样:
SELECT fk_id
FROM TableA
GROUP BY fk_id
HAVING GROUP_CONCAT(name) LIKE '%A%'
AND GROUP_CONCAT(name) NOT LIKE '%B%';
Basically, the result of GROUP_CONCAT(name)
with GROUP BY fk_id
returns the following:基本上,带有GROUP BY fk_id
的GROUP_CONCAT(name)
的结果返回以下内容:
+--------------------+-------+
| GROUP_CONCAT(name) | fk_id |
+--------------------+-------+
| C | l |
| A,B | m |
| A,C | n |
+--------------------+-------+
So we can make use of that result to do the filtering in HAVING
.所以我们可以利用该结果在HAVING
中进行过滤。 This query is similar to:此查询类似于:
SELECT fk_id
FROM
(SELECT GROUP_CONCAT(name) AS names, fk_id
FROM TableA
GROUP BY fk_id) A
WHERE names LIKE '%A%'
AND names NOT LIKE '%B%';
This instead is using a sub-query then doing the filtering afterward using WHERE
.相反,这是使用子查询,然后使用WHERE
进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.