简体   繁体   中英

How to search multiple tables in MySQL database for exact match using PHP

Here's the table structure

table : user
id
name
email
category

table 2 : body
id
uid
height
haircolor

Here's how i access the data from the database SELECT * FROM user WHERE category='paid' and with more codes it works.

What i want to do is like this (i..e allow complex search)

Select * FROM user WHERE category='paid' body.height='5ft', body.haircolor='red' WHERE user.id=body.uid

I know the statement is wrong, but i want the database to be searchable such that i can select haircolor as red, height as 5ft and the script should only return user(s) whose height is 5ft and haircolor is red (exact match)

I hope you guys understand my question.

PS : As you can see i have used 2 tables, 1 to store user info and 2 to store user body info. I can integrate them into 1 but i want to keep it as it is.

It looks like you have a bit of confusion based on using a WHERE for both the conditions of the select, as well as specifying the connection between your two tables. This is why I prefer to keep the joins explicitly defined, which would give you a query like this:

SELECT user.*
FROM user
JOIN body ON body.uid = user.id
WHERE body.height = '5ft'
    AND body.haircolor = 'red';

So now you've separated the part that connects the two tables out into the JOIN/ON section, and the WHERE only includes the conditions that narrow down the search.

You can actually do something very similar to what you're doing above - you just use multiple tables in your FROM construct. It's a great way when you want to pull something out quickly.

SELECT user.* FROM user, body 
    WHERE user.category = 'paid' 
    AND body.height = '5ft' 
    AND body.haircolor = 'red' 
    AND user.id = body.uid

Remember to specify the SELECT in this instance - everything from the user table. You could also do this with a JOIN, although I have a phobia of them so tend to use the previous method.

SELECT * FROM user 
    WHERE user.category = 'paid' 
    AND body.height = '5ft' 
    AND body.haircolor = 'red'
    JOIN body ON user.id = body.uid

That should do the trick! As I said, I despise using JOINs, and the former should be absolutely fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM