SQL匹配查询

时间:2012-07-02 11:38:58

标签: sql

我有两张桌子:

表a

ida     valuea
1       a
2       b
3       c
1       d
1       e
2       f

表b

idb      valueb
1 
2

我将valueb作为一个组合框,需要从一个选择valuea的查询中获取它,如果只有ida =当前idb.and表b变为:

表b

idb      valueb
1        (a,d,e)
2        (b,f)

2 个答案:

答案 0 :(得分:3)

很难确切地说出你在问什么,但我认为你要么只是寻找一个简单的内部联系:

SELECT  TableB.IDB, TableA.ValueA
FROM    TableB
        INNER JOIN TableA
            ON TableA.IDA = TableB.IDB

或者您需要将tableA中的行连接到IDB的单行。执行此操作的方法取决于DBMS,因为您没有指定我已经回答的DMBS。每个都有一个关于SQL Fiddle的例子。


<强> SQL-Server

SELECT  TableB.IDB,
        STUFF(( SELECT  ', ' + ValueA
                FROM    TableA
                WHERE   TableA.IDA = TableB.IDB
                FOR XML PATH(''), TYPE
                ).value('.', 'VARCHAR(MAX)'), 1, 2, '') AS ValueB
FROM    TableB

<强> MySQL / SQLite

SELECT  IDB, 
        GROUP_CONCAT(ValueA) AS ValueB
FROM    TableB
        INNER JOIN TableA
            ON TableA.IDA = TableB.IDB
GROUP BY IDB

<强> PostgreSQL

SELECT  IDB,
        ARRAY_AGG(ValueA) AS ValueB
FROM    TableB
        INNER JOIN TableA
            ON TableA.IDA = TableB.IDB
GROUP BY IDB

<强> Oracle

SELECT  IDB, 
        LISTAGG(ValueA, ', ') WITHIN GROUP (ORDER BY IDB) AS ValueB
FROM    TableB
        INNER JOIN TableA
            ON TableA.IDA = TableB.IDB
GROUP BY IDB

答案 1 :(得分:0)

SELECT distinct valuea
FROM tablea
WHERE ida = @idb

@idb是包含所选选项值的参数