Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

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

I have two MySQL tables something like this:

tool_owners:

tool_owners_id | user_id | ...


tools:

tools_id | tool_owners_id | tool_name | ...


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.

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.

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use a join

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...