![](/img/trans.png)
[英]Sort rows by column1 or column2 based on value in another column
[英]select rows based on column1 and column2 that have value of column 1
我有一个像这样的 SQL 表:
ID, ID2, category. date, txt
1 null 1 Y-m-d text
2 null 1 Y-m-d text
3 4 1 Y-m-d text
4 null 2 Y-m-d text
5 6 1 Y-m-d text
6 null 3 Y-m-d text
7 null 5 Y-m-d text
我尝试 select 所有类别 = 1 的行,例如 id: 1,2,3,5,6,但我也想要 id 为 4,6 的行,即使它们的类别不是 1,但它们在 ID2 的行中有类别 1。
Select * from table WHERE category=1 AND .... LIMIT 20
所以结果将是 1,2,3,4,5,6
在此处使用自加入:
SELECT t1.*
FROM yourTable t1
LEFT JOIN yourTable t2
ON t2.ID2 = t1.ID
WHERE
t1.category = 1 OR t2.category = 1;
你可以使用exists
select *
from t
where category=1
or exists (select * from t t2 where t2.id2=t.id and t2.category=1)
你想要的结果如何?
第一的:
select id t 来自测试 a,其中 a.category='1' 并且 id 不是 null
联合所有
select id2 t 来自测试 a,其中 a.category='1' 和 id2 不是 null
ID |
---|
1 |
2 |
3 |
5 |
4 |
6 |
第二:
select a.* from test a left join test b on a.id=b.id where a.category='1' or b.category='1'
ID | id2 | 类别 |
---|---|---|
1 | 1 | |
2 | 1 | |
3 | 4 | 1 |
5 | 6 | 1 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.