如果涉及两个表,如何检查行是否存在?

时间:2012-06-24 19:49:02

标签: php mysql

我有两个这样的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来自tools表。

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

使用联接

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'

答案 1 :(得分:0)

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'