通过id值从另一个表条件中存在的表中选择值

时间:2016-06-30 13:33:36

标签: mysql sql

我有两个表tablea和tableb

tablea(id PK)

id  value              
__________
1     a
2     b
3     c
4     d
5     e
6     f
7     g
8     h
9     i
10    j

tableb(id PK)

id  value
__________
1     a
2     d
3     c
4     h
5     e
6     f
7     j
8     d
9     d
10    j

我想通过id比较这些表 即{1,3,4,5,6} 如果tablea和tableb值的id是相同的,那么我想要返回的行数。

3 个答案:

答案 0 :(得分:2)

计算有多少行(由id连接)也具有相同的值:

SELECT count(*)
FROM tablea as a
  JOIN tableb as b ON a.id = b.id
WHERE a.value = b.value

答案 1 :(得分:1)

SELECT tablea.id
     , tablea.value AS valueA
     , tableb.value AS valueB
FROM tablea INNER JOIN tableb
  ON tablea.id = tableb.id
WHERE tablea.value = tableb.value
  AND tablea.id IN(1,3,4,5,6)

然后你也可以计算行数:

SELECT COUNT(*) AS commonRows
FROM tablea INNER JOIN tableb
  ON tablea.id = tableb.id
WHERE tablea.value = tableb.value
  AND tablea.id IN(1,3,4,5,6)

答案 2 :(得分:0)

SELECT COUNT(*)
FROM tablea a
INNER JOIN tableb b ON a.id=b.id AND a.value=b.value;