当涉及两个表时如何检查一行是否存在? [英] How to check if a row exists when there are two tables involved?

查看:40
本文介绍了当涉及两个表时如何检查一行是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个像这样的 MySQL 表:

I have two MySQL tables something like this:

tool_owners:

tool_owners:

tool_owners_id | user_id | ...


工具:

tools_id | tool_owners_id | tool_name | ...


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

I have the user_id and tool name. I need to check to see if the user owns a specific tool. The challenge is that these bits of information (the user_id and tool_name) are in separate tables, where the rows are linked by tool_owners_id.

如果有人想知道,我不能改变表格的结构.

In case anyone is wondering, I can't change the structure of the tables.

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

Is what I'm asking possible? The only way I know how to do this is to make a first query getting the tool_owners_id from the tool_owners table, then a second query doing COUNT(*) where the tool_owners_id = xxx AND tool_name = xxxx from the tools table.

感谢您的帮助!

推荐答案

使用连接

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'

这篇关于当涉及两个表时如何检查一行是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆