[英]MYSQL count first table ids where value is found in second table
I have two tables, 我有两张桌子
table1 and table2 both tables has these columns table1和table2这两个表都有这些列
id, name, rel_id
now i would like to have a query to count ids of the table1 where name from table2 is equals to john and table1 rel_id equals to table2 rel_id. 现在我想查询一个查询table1的 id,其中table2的名称等于john, table1 rel_id等于table2 rel_id。 so something like this (this is not correct that's why i need help to make it work).
所以这样的事情(这是不正确的,这就是为什么我需要帮助才能使其工作)。
Select count(ids) from table1
where table2.name="john"
and table1.rel_id=table2.rel_id
Well, one way is to use a join: 好吧,一种方法是使用联接:
Select count(t1.id)
from table1 t1 join
table2 t2
on t1.rel_id = t2.rel_id
where t2.name = 'john';
Note that this uses table aliases to distinguish all the columns in each table. 请注意,这使用表别名来区分每个表中的所有列。 Because the tables have the same columns, you need to identify the table for each column.
由于表具有相同的列,因此您需要为每个列标识表。 Also, the I changed the string constant to use single quotes rather than double quotes.
另外,我将字符串常量更改为使用单引号而不是双引号。
You need to look into joins so : 您需要研究联接,以便:
select count(ids) from table1 join table2 on table1.rel_id=table2.rel_i where table2.name="john"
A short intro from W3C schools: http://www.w3schools.com/sql/sql_join.asp W3C学校的简短介绍: http : //www.w3schools.com/sql/sql_join.asp
The full MySQL URL for more reference http://dev.mysql.com/doc/refman/5.0/en/join.html 完整的MySQL URL,供更多参考http://dev.mysql.com/doc/refman/5.0/en/join.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.