【问题标题】:How to check if a row exists when there are two tables involved?当涉及两个表时如何检查一行是否存在?
【发布时间】:2012-06-25 04:34:48
【问题描述】:

我有两个类似这样的 MySQL 表:

工具所有者:

tool_owners_id | user_id | ...


工具:

tools_id | tool_owners_id | tool_name | ...


我有 user_id 和工具名称。我需要检查用户是否 拥有特定的工具。挑战在于这些信息(user_id 和 tool_name)位于不同的表中,其中的行由 tool_owners_id 链接。

如果有人想知道,我无法更改表格的结构。

我问的可能吗?我知道如何做到这一点的唯一方法是进行第一个查询,从 tool_owners 表中获取 tool_owners_id,然后从 tools 表中执行 COUNT(*) 的第二个查询,其中 tool_owners_id = xxx AND tool_name = xxxx。

感谢您的帮助!

【问题讨论】:

  • 谷歌“MySQL JOINs”,你会成为一个非常非常快乐的程序员。
  • 您想关联 user_id 和 tool_name 吗?

标签: php mysql


【解决方案1】:

使用连接

SELECT * 
FROM table1 
LEFT JOIN table2 
    ON table1.tool_owners_id=table2.tool_owners_id 
WHERE table1.user_id=1 
AND table2.tool_name='hammer'

【讨论】:

    【解决方案2】:
    select count(o.*) 
    from tool_owners o
    inner join tools t on t.tools_owners_id = o.tools_owners_id
    where o.user_id = 123
    and t.tool_name = 'toolname'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      相关资源
      最近更新 更多