gpt4 book ai didi

mysql 选择是否存在一对多

转载 作者:行者123 更新时间:2023-11-29 08:40:38 25 4
gpt4 key购买 nike

如何检查多对一关系是否已经存在?

SampleTable
╔════╦═══════╗
║ ID ║ OB_ID ║
╠════╬═══════╣
║ 1 ║ 1 ║
║ 1 ║ 2 ║
║ 2 ║ 3 ║
║ 2 ║ 1 ║
║ 2 ║ 2 ║
║ 3 ║ 1 ║
║ 3 ║ 3 ║
╚════╩═══════╝

我想搜索 SampleTable.ob_id 并选择 SampleTable.id(如果存在)。

搜索 (1,2)
返回1;

╔════╗
║ ID ║
╠════╣
║ 1 ║
╚════╝

搜索(1,2,3)
返回2;

╔════╗
║ ID ║
╠════╣
║ 2 ║
╚════╝

搜索 (2,3)
返回空记录集(或 null)

╔════╗
║ ID ║
╚════╝

最佳答案

SELECT ID
FROM tableName a
WHERE ob_id IN (1,2,3)
GROUP BY ID
HAVING COUNT(*) =
(
SELECT COUNT(*)
FROM TableName b
WHERE b.ID = a.ID
) AND
COUNT(*) = 3 -- the value of this depend on the number of values
-- you have supplied on you where clause.

如果没有为每个IDob_ID定义唯一约束,则需要使用DISTINCT

SELECT ID
FROM tableName a
WHERE ob_id IN (1,2)
GROUP BY ID
HAVING COUNT(DISTINCT ob_id) =
(
SELECT COUNT(DISTINCT ob_id)
FROM TableName b
WHERE b.ID = a.ID
) AND
COUNT(DISTINCT ob_id) = 2

关于mysql 选择是否存在一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13892275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com