从 table1 中选择不在 table2 中的列
Posted
技术标签:
【中文标题】从 table1 中选择不在 table2 中的列【英文标题】:Select column from table1 which is not in table2 【发布时间】:2020-04-22 03:38:26 【问题描述】:我有两张桌子
table1
=======================================
tid subcategory category
---------------------------------------
1 SUBCATEGORY1 CATEGORY1
2 SUBCATEGORY1 CATEGORY2
3 SUBCATEGORY2 CATEGORY1
4 SUBCATEGORY3 CATEGORY1
5 SUBCATEGORY4 CATEGORY1
6 SUBCATEGORY5 CATEGORY1
7 SUBCATEGORY6 CATEGORY1
8 SUBCATEGORY7 CATEGORY1
9 SUBCATEGORY8 CATEGORY1
10 SUBCATEGORY9 CATEGORY1
table2
=======================================
t2id subcategory category pid
---------------------------------------
1 SUBCATEGORY1 CATEGORY1 1
2 SUBCATEGORY1 CATEGORY2 1
3 SUBCATEGORY2 CATEGORY1 1
我尝试显示table1中不在table2中的所有行,结果应该是这样的...
=======================================
tid subcategory category
---------------------------------------
4 SUBCATEGORY3 CATEGORY1
5 SUBCATEGORY4 CATEGORY1
6 SUBCATEGORY5 CATEGORY1
7 SUBCATEGORY6 CATEGORY1
8 SUBCATEGORY7 CATEGORY1
9 SUBCATEGORY8 CATEGORY1
10 SUBCATEGORY9 CATEGORY1
我正在使用这个查询...
select tl.* from table1 tl where subcategory and category not in(SELECT tl.subcategory, tl.category FROM table1 as tl join table2 as bm where bm.pid='1' and tl.subcategory=bm.subcategory and tl.category=bm.category);
但它不起作用请帮助...
【问题讨论】:
【参考方案1】:我会在这里使用存在逻辑:
SELECT t1.tid, t1.subcategory, t1.category
FROM table1 t1
WHERE NOT EXISTS (SELECT 1 FROM table2 t2
WHERE t2.pim = 1 AND
t2.subcategory = t1.subcategory AND t2.category = t1.category);
【讨论】:
你能告诉我SELECT 1是什么意思SELECT 1
只会返回一个记录,其中包含一个值为 1 的列,但这里的逻辑是检查 WHERE
子句中的条件是否存在。有关语法的更多信息,请阅读存在。以上是关于从 table1 中选择不在 table2 中的列的主要内容,如果未能解决你的问题,请参考以下文章