简体   繁体   English

MYSQL计算第一个表的ID,在第二个表中找到值

[英]MYSQL count first table ids where value is found in second table

I have two tables, 我有两张桌子

table1 and table2 both tables has these columns table1table2这两个表都有这些列

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.

相关问题 从第一个表中选择所有内容并从第二个表中按 Count(id) 排序,其中 second.value = 1 - Select all from first table and order by Count(id) from second table where second.value = 1 MYSQL:两个表之间的UNION结果,如果在第二个表中找到PK,则从第一个表中删除记录 - MYSQL: UNION results between two tables where omitting records from first table if PK found in second table MySQL选择ID匹配的另一个表的行数 - MySQL select count of another table's rows where the IDs match MySQL使用第二个表ID更新一个表 - mysql update one table with second table ids 查找第一个表中与第二个表的行ID与最大日期匹配的行数 - Find count of rows in first table that match ids of row of second table with max date 计算没有“-” mysql的值不在另一个表中的位置 - count where value not in another table without '-' mysql 从一个表中选择行,其中基于第二个表ID的另一个第二个表中的ID显示结果的顶部以及下一个结果,因为它是+ Mysql - Select rows from a table where id in another second table based on second table ids shows results top as well as next results as it is + Mysql mysql从第一个表中的列更新第二个表中列的行,其中第一个表中的另一列与第二个表中的列匹配 - mysql update rows of column in second table from column in first table where another column in first table matches column in second table MySQL从第二个表计数 - Mysql count from a second table 带有表连接的MySQL查询,其中第二个表名称来自第一个表中的列 - MySQL query with joins on a table where second table name comes from a column in the first table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM