mysql 左加入和搜索
mysql left join and search
我有以下数据集:http://sqlfiddle.com/#!9/6f4751/3
只是我需要得到 law_court_mesul_shexs
.cif
是 008003 和 516561
的法庭
SELECT
distinct `law_court_mesul_shexs`.`court_id`,
`law_court`.*
FROM `law_court`
LEFT JOIN `law_court_mesul_shexs`
ON `law_court`.`court_id` = `law_court_mesul_shexs`.`court_id`
WHERE `law_court_mesul_shexs`.`cif` = '008003'
OR `law_court_mesul_shexs`.`cif`= '516561'
这个 sql 有效,但它也 returns court id 114 因为 114 也有 CIF 008003。
但我只想获得法院编号 113,因为我需要获得只有 CIF 为 008003 和 516561 的法院。
您可以使用以下方法来获得您想要的结果集
SELECT `c`.*
FROM `law_court` c
JOIN (SELECT court_id
FROM law_court_mesul_shexs
WHERE cif IN('008003' , '516561')
GROUP BY court_id
HAVING COUNT(DISTINCT mesul_shexs_id) = 2
) s
ON `c`.`court_id` = `s`.`court_id`;
或
SELECT `c`.*
FROM `law_court` c
JOIN (SELECT court_id
FROM law_court_mesul_shexs
WHERE cif IN('008003' , '516561')
GROUP BY court_id
HAVING SUM(cif ='008003') > 0
AND SUM(cif ='516561') > 0
) s
ON `c`.`court_id` = `s`.`court_id`
或使用exists
SELECT `c`.*
FROM `law_court` c
WHERE EXISTS (
SELECT 1
FROM law_court_mesul_shexs
WHERE cif = '008003' AND court_id = c.court_id
) AND (
SELECT 1
FROM law_court_mesul_shexs
WHERE cif = '516561' AND court_id = c.court_id
)
我有以下数据集:http://sqlfiddle.com/#!9/6f4751/3
只是我需要得到 law_court_mesul_shexs
.cif
是 008003 和 516561
SELECT
distinct `law_court_mesul_shexs`.`court_id`,
`law_court`.*
FROM `law_court`
LEFT JOIN `law_court_mesul_shexs`
ON `law_court`.`court_id` = `law_court_mesul_shexs`.`court_id`
WHERE `law_court_mesul_shexs`.`cif` = '008003'
OR `law_court_mesul_shexs`.`cif`= '516561'
这个 sql 有效,但它也 returns court id 114 因为 114 也有 CIF 008003。
但我只想获得法院编号 113,因为我需要获得只有 CIF 为 008003 和 516561 的法院。
您可以使用以下方法来获得您想要的结果集
SELECT `c`.*
FROM `law_court` c
JOIN (SELECT court_id
FROM law_court_mesul_shexs
WHERE cif IN('008003' , '516561')
GROUP BY court_id
HAVING COUNT(DISTINCT mesul_shexs_id) = 2
) s
ON `c`.`court_id` = `s`.`court_id`;
或
SELECT `c`.*
FROM `law_court` c
JOIN (SELECT court_id
FROM law_court_mesul_shexs
WHERE cif IN('008003' , '516561')
GROUP BY court_id
HAVING SUM(cif ='008003') > 0
AND SUM(cif ='516561') > 0
) s
ON `c`.`court_id` = `s`.`court_id`
或使用exists
SELECT `c`.*
FROM `law_court` c
WHERE EXISTS (
SELECT 1
FROM law_court_mesul_shexs
WHERE cif = '008003' AND court_id = c.court_id
) AND (
SELECT 1
FROM law_court_mesul_shexs
WHERE cif = '516561' AND court_id = c.court_id
)