【问题标题】:MYSQL count first table ids where value is found in second tableMYSQL 计算在第二个表中找到值的第一个表 id
【发布时间】:2014-04-17 23:10:59
【问题描述】:

我有两张桌子,

table1table2 两个表都有这些列

id, name, rel_id

现在我想要一个查询来计算 table1 的 ID,其中 table2 中的名称等于 john 并且 table1 rel_id 等于到 table2 rel_id。 所以这样的事情(这是不正确的,这就是为什么我需要帮助才能使它工作)。

Select count(ids) from table1
where table2.name="john" 
and table1.rel_id=table2.rel_id

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    嗯,一种方法是使用连接:

    Select count(t1.id)
    from table1 t1 join
         table2 t2
         on t1.rel_id = t2.rel_id
    where t2.name = 'john';
    

    请注意,这使用表别名来区分每个表中的所有列。由于表具有相同的列,因此您需要为每一列标识表。另外,我将字符串常量更改为使用单引号而不是双引号。

    【讨论】:

    • +1 :这可能需要不同的计数,具体取决于数据。
    【解决方案2】:

    您需要查看连接:

    select count(ids) from table1 join table2 on table1.rel_id=table2.rel_i where table2.name="john"

    来自 W3C 学校的简短介绍:http://www.w3schools.com/sql/sql_join.asp

    完整的 MySQL URL 以供参考http://dev.mysql.com/doc/refman/5.0/en/join.html

    【讨论】:

    • 感谢您的宝贵时间和有用的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多