简体   繁体   中英

Php mysql query for data from two tables

i have two tables in my database. table A is USERS and table B is relations, and the following are their columns USERS(username, avatar, specialty) and RELATIONS(username1, username2, reldir) RELATIONS stores the relationship between users, that is if, username1 is following username2, reldir = F, and if they are both following each other, reldir=FB and vice versa, this part has worked very well but

i need to query these tables so that i return a list of users from USERS which for example user A doesnt follow but have the same specialty as A...

i tried this, but its not working well ...

$spec = the specialty of user A

SELECT a.username, a.avatar, a.specialty FROM users a, relations b WHERE a.username!=b.username2 AND (b.reldir!='F' OR b.reldir!='FB') AND a.speciality ='$spec'

the query to me seems logically correct but i could be wrong. i need help

You need to add some keys for your tables, because you have two different tables and they doesn't linked.

For example, table USERS :

id (as primary_key), username, avatar, specialty

Table RELATIONS :

user_id, username2, reldir

user_id - it is field "id" from table USERS (instead your "username1")

Then you will be able create a query like this:

SELECT a.* 
FROM users a, relations b 
WHERE a.id = b.users_id 
  AND (b.reldir != 'F' OR b.reldir != 'FB') 
  AND a.speciality = '$spec'

ps: if I understood your question in the right way)

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