开发者

SQL: SELECT if entry in one column corresponds to another column of a different table

I have two tables in my database. The first one, [nodeActivity] has the following two columns ( primary Key = node_name )

node_name | last_updated |
          |              |
node 1    |  00:00:00    |
node 2    |  00:00:01    |

The second, table called [nodes] has the following columns ( no primary key )

node_name |  data   |  time     |
          |         |           | 
node 1    |  data1  |  00:00:01 |    
node 2    |  data2  |  00:00:01 |     
node 1    |  data3  |  00:00:02 |    
node 2    |  data5  |  00:00:02 |    
node 1    |  data6  |  00:00:03 |
node 3    |  data7  |  00:00:03 |      

I want to select only those nodes and data from [nodes], which have a corresponding entry in the [nodeActivity] table.

For example, In the above case, I want to exclude node3 and data7, as node3 is not present in [nodeActivity]. How 开发者_JAVA百科can the above can be accomplished, in the most efficient manner possible?


SELECT DISTINCT n.node_name, n.data
    FROM nodes n
        INNER JOIN nodeActivity na
            ON n.node_name = na.node_name
                AND na.time = '00:00:00'


select * from nodes where node_name in (select node_name from nodeActivity)


This should work

SELECT DISTINCT n.* FROM [nodes] AS n
INNER JOIN [nodeActivity] AS na
ON n.node_name = na.node_name

Hope this helps.

See the new query to select unquie rows.


SELECT n.node_name, n.last_updated, na.data, na.time
FROM [nodes] n
INNER JOIN [nodeActivity] na ON n.node_name = na.node_name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜