当涉及两个表时,如何检查行是否存在


How to check if a row exists when there are two tables involved?

>我有两个MySQL表,如下所示:

tool_owners:

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,然后执行第二个查询 COUNT(*),其中tool_owners_id = xxx AND tool_name = xxxx 来自工具表。

感谢您的帮助!

使用连接

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'
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'