我有两个表
表1
+-----------+----------+
| support_id| Name |
+-----------+----------+
| 1 | Name 1 |
| 2 | Name 2 |
+-----------+----------+
表2
+-----------+----------+
| school_id | support_id|
+-----------+----------+
| 2314 | 1 |
+-----------+----------+
期望输出
+-----------+----------+------------+
| school_id |support_id| has |
+-----------+----------+------------+
| 2314 | 1 | Yes |
| 2314 | 2 | No |
+-----------+----------+------------+
如何添加第三行告诉我表2是否在表1中?
谢谢!
答案 0 :(得分:0)
表1在表2中是什么意思? 字段support_id与表2中的support_id相同吗? 还是字段或school_id相同?
两个表中的字段必须相同,以便建立连接(外键),进行联接并连接两个表。
考虑将support_id作为Foreigh键(两个表之间共享的值),您可以使用以下选择:
SELECT school_id, IF(support_id is not null, "Yes", "No") as Has
FROM table1 LEFT JOIN table2
ON table1.support_id = table2.support_id;
答案 1 :(得分:0)
我将使用左联接,然后使用case
表达式来格式化结果:
SELECT t2.*, CASE WHEN t1.support_id IS NOT NULL THEN 'Yes' ELSE 'No' END
FROM t2
LEFT JOIN t1 ON t2.support_id = t1.support_id