我有两张表:categories
和prodvscats
categories prodvscats
id | id
title | categories_id
每个表都有一些行,例如:
categories prodvscats
categ1 | categ1
categ2 | categ2
categ3
categ4
我想返回所有类别,但我想知道prodvscats
表中存在哪些类别。
期望的结果:
title boolean variable exists
categ1 | 1
categ2 | 1
categ3 | 0
categ4 | 0
我尝试使用join
,但它只返回前两行。也许它需要像个案一样,但我不知道该怎么做。
SELECT categories.id, categories.title
FROM categories
INNER JOIN prodvscats ON prodvscats.categories_id = categories.id
ORDER BY id
答案 0 :(得分:1)
使用LEFT JOIN
加入这两个表。这将返回所有行,包括其他表中不存在类别的行。然后使用GROUP BY
合并类别和COUNT
以确定是否存在匹配项:
SELECT
categories.id,
categories.title,
CASE WHEN COUNT(prodvscats.id) = 0 THEN 0 ELSE 1 END AS product_exists
FROM categories
LEFT JOIN prodvscats ON categories.id = prodvscats.categories_id
GROUP BY categories.id, categories.title
答案 1 :(得分:1)
试试这个
SELECT categories.id, categories.title,
IF(prodvscats.categories_id IS NULL, '0', '1') AS exists_value
FROM categories
LEFT JOIN prodvscats ON prodvscats.categories_id = categories.id
ORDER BY id