我使用MySQL,我想根据subQuery的结果过滤table1的结果。我所做的就是2个查询,但不相同。
第一个查询将为我提供用户的所有类别: 查询1
SELECT
`category-id` as `id`
FROM
`categories-in-teams` as cit
JOIN
`user-role-teams` AS urt ON cit.`team-id` = urt.`team-id`
WHERE
urt.`user-id` = 62
结果如下:
100
200
300
400
现在,在我的第二个请求中,我获得了包含一些其他数据的整个类别列表: 查询2
SELECT
cat.`id`,
loc.`name`,
cat.`parent`,
pcat.`id` IS NULL as leaf
FROM
`product-category` AS cat
LEFT JOIN
`product-category` as pcat ON cat.`id` = pcat.`parent`
JOIN
`product-category-local` as loc ON cat.`id` = loc.`category-id`
AND loc.`lang-id` = 1
GROUP BY cat.`id`
ORDER BY cat.`parent` , `name`
输出:
id name parent leaf
1 Root null 0
2 Bathroom 1 0
3 Bedroom 1 0
100 pillow 3 1
200 sofa 3 1
300 blanket 3 1
400 dunno 3 1
我想从第二个查询获得的结果将从第一个查询中获取结果并排除leaf
= 0且id
不在{{parent
上的所有行(类别) 1}}列。
因此,从上面的例子中,预期的结果将是:
id name parent leaf
1 Root null 0
3 Bedroom 1 0
100 pillow 3 1
200 sofa 3 1
300 blanket 3 1
400 dunno 3 1
答案 0 :(得分:0)
试试这个:
SELECT
cat.`id`,
loc.`name`,
cat.`parent`,
pcat.`id` IS NULL as leaf
FROM
`product-category` AS cat
LEFT JOIN
`product-category` as pcat ON cat.`id` = pcat.`parent`
JOIN
`product-category-local` as loc ON cat.`id` = loc.`category-id`
AND loc.`lang-id` = 1
WHERE cat.`id` IN (
SELECT
`category-id` as `id`
FROM
`categories-in-teams` as cit
JOIN
`user-role-teams` AS urt ON cit.`team-id` = urt.`team-id`
WHERE
urt.`user-id` = 62
)
OR
((pcat.`id` = 0) AND (cat.`id` IN (SELECT parent FROM `product-category`)) )
GROUP BY cat.`id`
ORDER BY cat.`parent` , `name`