2011-06-10 81 views
1

我有以下2個表..SQL交叉搜索兩個表

mysql> describe catalog_category_reference; 
+----------+---------+------+-----+---------+----------------+ 
| Field | Type | Null | Key | Default | Extra   | 
+----------+---------+------+-----+---------+----------------+ 
| id  | int(11) | NO | PRI | NULL | auto_increment | 
| name  | text | NO |  | NULL |    | 
| class_id | text | NO |  | NULL |    | 
+----------+---------+------+-----+---------+----------------+ 

mysql> describe product_import_queue; 
+-----------------------+---------+------+-----+---------+----------------+ 
| Field     | Type | Null | Key | Default | Extra   | 
+-----------------------+---------+------+-----+---------+----------------+ 
| id     | int(11) | NO | PRI | NULL | auto_increment | 
| unique_id    | text | NO |  | NULL |    | 
| category_code   | text | NO |  | NULL |    | 
| item_code    | text | NO |  | NULL |    | 
| ffl_flag    | int(11) | NO |  | NULL |    | 
| name     | text | NO |  | NULL |    | 
| price     | text | NO |  | NULL |    | 
| image     | text | NO |  | NULL |    | 
| custom_options_flag | int(11) | NO |  | NULL |    | 
| custom_options_string | text | NO |  | NULL |    | 
| short_desc   | text | NO |  | NULL |    | 
| long_desc    | text | NO |  | NULL |    | 
| process_status  | int(11) | NO |  | 0  |    | 
+-----------------------+---------+------+-----+---------+----------------+ 

我想通過product_import_queue搜索並找到「category_code」的不存在中catalog_Category_reference。請注意,category_code存儲在class_id下的catalog_reference表中。我可以在一個查詢中做到這一點嗎?我試過類似的東西...

SELECT category_code FROM product_import_queue 
LEFT JOIN catalog_category_reference ON product_import_queue.category_code = catalog_category_reference.class_id; 

但那不是我正在尋找,我不完全理解JOIN的呢。

回答

5

你幾乎沒有...只需要添加一個where子句...

SELECT category_code 
FROM product_import_queue 
     LEFT JOIN catalog_category_reference 
     ON product_import_queue.category_code = 
      catalog_category_reference.class_id 
WHERE catalog_category_reference.class_id IS NULL 
+0

啊,這工作完美!謝謝 :) – 2011-06-10 19:46:27

1
SELECT category_code FROM product_import_queue 
LEFT JOIN catalog_category_reference ON product_import_queue.category_code = catalog_category_reference.class_id 
WHERE catalog_category_reference.class_id is null 
0
SELECT category_code FROM product_import_queue LEFT JOIN catalog_category_reference ON product_import_queue.category_code = catalog_category_reference.class_id WHERE catalog_category_reference.class_id IS NULL 

這個查詢只能找到產品queque其中category_code不在類參考