检查/匹配两个不同表格中的ID

时间:2017-11-03 12:36:47

标签: sql sqlite join

我有一个带有两个表的SQLite数据库,我想合并/ FULL JOIN这些表。 sqlfiddle这个问题。

表1:

CREATE TABLE cp_product(
  `id` INTEGER PRIMARY KEY,
  `title` TEXT,
  `category_id` INTEGER,
  `locked` INTEGER
);

enter image description here

表2将产品ID作为外键(brand_id):

CREATE TABLE cp_observation_strength_of_demands(
  `id` TEXT PRIMARY KEY,
  `brand_id` INTEGER,
  `sold_level` INTEGER,
  `visit_id` TEXT,
  `status` INTEGER,
   FOREIGN KEY(brand_id) REFERENCES cp_product(id)
);

enter image description here

我正在尝试合并两个表。我想创建新列说测试,如果表2具有表1中的brand_id,我希望该列存储为true,否则为false。像这样:

enter image description here

由于SQLite不支持FULL JOIN我使用UNION ALL创建了一个查询,但它返回了所有ID,尽管表2中已经出现。我的查询如下:

SELECT A.*, B.* FROM cp_observation_strength_of_demands A LEFT JOIN cp_product B ON A.brand_id = B.id 
UNION ALL
SELECT A.*, B.* FROM cp_observation_strength_of_demands A LEFT JOIN cp_product B ON A.brand_id = B.id
WHERE B.category_id = 4 and A.sold_level = 1

0 个答案:

没有答案
相关问题