我是SQL的新手并遇到以下挑战,我左边有一个表,它将产品分配给一家公司并用ref_id表示(它来自另一个表,我为了提问而对其进行了简化) )我有一个主列表。我想将公司“A”的所有产品与主列表进行比较,并显示公司A尚未订阅的所有产品。我正在使用JOIN并最终获得重复的列名称,这会引发我的PHP程序。以下是我为UNION,RIGHT JOIN,LEFT JOIN和NOT运算符尝试了几种语法,以下是我得到的最接近的,但是我得到了重复的列名,我只需要最后两列的最后一个表。请指教。
mysql> select ref_id, product_id, short_name from ap_company_product order by ref_id, product_id;
+--------+------------+------------+
| ref_id | product_id | short_name |
+--------+------------+------------+
| 2 | 10 | product 10 |
| 2 | 11 | product 11 |
| 2 | 12 | product 12 |
| 2 | 15 | product 15 |
| 2 | 17 | product 17 |
| 2 | 21 | product 21 |
| 3 | 11 | product 11 |
| 3 | 13 | product 13 |
| 3 | 17 | product 17 |
| 3 | 20 | product 20 |
+--------+------------+------------+
10 rows in set (0.00 sec)
THE MAIN LIST
mysql> select product_id, short_name from ap_company_product_list;
+------------+-------------+
| product_id | short_name |
+------------+-------------+
| 10 | product 10 |
| 11 | product 11 |
| 12 | product 12 |
| 13 | product 13 |
| 14 | product 14 |
| 15 | product 15 |
| 16 | product 16 |
| 17 | product 17 |
| 18 | product 18 |
| 19 | product 19 |
| 20 | product 20 |
| 21 | product 21 |
| 22 | product 22 |
+------------+-------------+
13 rows in set (0.00 sec)
Another SQL which is the actual results I need
SELECT aa.product_id as product_id, aa.short_name as short_name, aa.ref_id as ref_id, bb.product_id as product_id, bb.short_name as short_name FROM (select ref_id, product_id, short_name from ap_company_product where ref_id=2) aa RIGHT OUTER JOIN ap_company_product_list bb ON aa.product_id = bb.product_id where aa.product_id is NULL;
+------------+------------+--------+------------+------------+
| product_id | short_name | ref_id | product_id | short_name |
+------------+------------+--------+------------+------------+
| NULL | NULL | NULL | 13 | product 13 |
| NULL | NULL | NULL | 14 | product 14 |
| NULL | NULL | NULL | 16 | product 16 |
| NULL | NULL | NULL | 18 | product 18 |
| NULL | NULL | NULL | 19 | product 19 |
| NULL | NULL | NULL | 20 | product 20 |
| NULL | NULL | NULL | 22 | product 22 |
+------------+------------+--------+------------+------------+
7 rows in set (0.01 sec)
答案 0 :(得分:2)
请使用:
SELECT bb.product_id as product_id, bb.short_name as short_name FROM (select ref_id, product_id, short_name from ap_company_product where ref_id=2) aa RIGHT OUTER JOIN ap_company_product_list bb ON aa.product_id = bb.product_id where aa.product_id is NULL;
顺便说一下,我更喜欢这个:
SELECT product_id, short_name FROM ap_company_product_list WHERE product_id NOT IN (SELECT product_id FROM ap_company_product);