如果包含在另一个子查询中,则使用where子句子查询返回要检查的多行的select语句

时间:2018-02-06 05:30:19

标签: mysql sql

这大致是我一直在努力做的事情,我似乎无法弄清楚如何让它发挥作用。

SELECT a.name FROM tableA a, TableB b
WHERE a.key = b.key
AND (SELECT b.values FROM tableA a, TableB b
     WHERE a.key = b.key
     AND a.name = Prime_Key) IN 
     (SELECT b.values FROM tableA a, TableB b WHERE a.key = b.key)

我有两个表,从tableA到tableB有一对多的关系。我需要一个select,它从tableB中找到tableA中的特定名称的所有值,然后查找所有与所有值相关联的名称。因此,最终输出将是一个名称列表,其中包含指向给定Prime_Key所具有的所有值的链接。

一些样本数据将是:

表A:

name    key
Bob     1
Alice   2
Mark    3
Jill    4
Luke    5

和tableB:

key value
1   short
1   boy
2   tall
2   girl
2   blond
3   short
3   brownhair
3   boy
3   golf
4   girl
5   golf
5   boy
5   brownhair

因此,如果我用Bob替换Prim_Key,结果将是Mark,因为他有两个值短和男孩。同样,如果Prim_Key为Mark,则没有返回,因为没有其他人拥有他所做的所有值

2 个答案:

答案 0 :(得分:1)

您可以使用子查询联接+计数匹配来实现结果:

SELECT 
    person_name, 
    sum(total_match) total_matches, 
    num_attributes

FROM (

    SELECT 
        search_name,
        search_value, 
        num_attributes, 
        person_name, 
        sum(is_match) total_match
    FROM (

        SELECT
            search_subject.name as search_name,
            search_subject.value as search_value,
            search_subject.total_attributes as num_attributes,
            people.name as person_name,
            people.value as person_value,
            IF(search_subject.value=people.value,1,0) as is_match

        FROM (

            SELECT 
                name, 
                value, 
                total_attributes
            FROM tablea
            JOIN tableb USING(`key`)
            JOIN (

                SELECT count(*) total_attributes
                FROM tablea
                JOIN tableb using(`key`)
                WHERE name = 'Bob'

            ) attributes_count
            WHERE name = 'Bob'

        ) search_subject

        JOIN (

            SELECT  
                name, 
                value
            FROM tablea
            JOIN tableb using(`key`)

        ) people ON ( search_subject.name <> people.name)

    ) x
    GROUP BY search_name, search_value, person_name

) y
GROUP BY person_name
HAVING total_matches = num_attributes

答案 1 :(得分:0)

首先,我使用GROUP_CONCAT函数将每个键的值分组为一个,同时为like子句创建模式。

SELECT key, 
       GROUP_CONCAT(VALUE ORDER BY VALUE DESC SEPARATOR '%' ) AS myValues
FROM tableB
GROUP BY key;

结果会像这样:

key value
1   boy%short
2   blond%girl%tall
3   boy%brownhair%golf%short
4   girl
5   boy%brownhair%golf

然后创建类似查询以获取结果。为简单起见,您可以使用以下方法创建视图:

CREATE VIEW table_ab AS (SELECT key, GROUP_CONCAT(VALUE ORDER BY VALUE DESC SEPARATOR '%' ) AS myValues
FROM tableB
GROUP BY key);

最后,您可以通过以下方式获得结果:

SELECT 
  t2.name 
FROM
table_ab t1 
  LEFT JOIN test_a t2 
ON t1.key = t2.key
WHERE t1.myvalues LIKE 
 (SELECT myvalues FROM table_ab WHERE key = (SELECT key FROM test_a a WHERE a.name = 'Bob')) AND t2.name != 'Bob'