简体   繁体   中英

How do I join these 3 tables and make my Select query work?

I have 2 tables:

review_shared:

review_shared_id    cat_id    user_id     contact_id
19                   5        10276       10275
20                   5        10276       10277
21                   5        10276       10273
15                   6        10279       10277

category:

cat_id    user_id    cat_name
  3        10278        A
  4        10279        B
  5        10276        C
  6        10279        D        

I carry out my query with:

$sql = "
SELECT * 
  FROM review_shared 
  JOIN category 
    ON review_shared.cat_id = category.cat_id 
 WHERE review_shared.contact_id = ?
";

With review_shared.contact_id as 10277 , the above would give me:

review_shared.                                 category.
review_shared_id  cat_id  user_id  contact_id  cat_id  user_id  cat_name
    20                5       10276    10277       5       10276    C
    15                6       10279    10277       6       10279    D

Now I have a third table, contacts :

contact_auto_inc   user_id  contact_id
1                   10278    10273
2                   10277    10276
3                   10261    10285

if the contacts table has a row with user_id as 10277 and contact_id as the user_id value in review_shared table then I want to return these values. So in the case above the result would be (with review_shared.contact_id = ? as 10277 ):

review_shared.                                 category.
        review_shared_id  cat_id     user_id  contact_id  cat_id  user_id  cat_name  contact_auto_inc   user_id  contact_id
            20                5       10276    10277       5       10276    C          2                 10277    10276

This is the statement I am using but it doesn't seem to be be working:

$sql = "
SELECT * 
  FROM review_shared 
  JOIN category 
    ON review_shared.cat_id = category.cat_id 
  JOIN contacts 
    ON review_shared.contact_id = contacts.user_id 
   AND contacts.contact_id = review_shared.user_id
 WHERE review_shared.contact_id = ?
";

you have an error on the contact join:

$sql = "
SELECT * 
  FROM review_shared 
  JOIN category 
    ON review_shared.cat_id = category.cat_id 
  JOIN contacts 
    ON review_shared.contact_id = contacts.contact_id
 WHERE review_shared.contact_id = ?
";

Alternative you can try a equiJoin Like:

SELECT * 
FROM review_shared r, category c, contacts p,
WHERE r.cat_id = c.cat_id 
AND p.contact_id = r.user_id
AND r.contact_id = ?

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