![](/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.