我有2张桌子:
评论共享:
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
类别:
cat_id user_id cat_name
3 10278 A
4 10279 B
5 10276 C
6 10279 D
我通过以下方式进行查询
$sql = "
SELECT *
FROM review_shared
JOIN category
ON review_shared.cat_id = category.cat_id
WHERE review_shared.contact_id = ?
";
将review_shared.contact_id
设为10277
,上面的代码会给我:
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
现在我有了第三个表contacts
:
contact_auto_inc user_id contact_id
1 10278 10273
2 10277 10276
3 10261 10285
如果contacts
表中有一行,user_id
表中的10277
为contact_id
,而user_id
为review_shared
的值,那么我要返回这些值。因此,在上述情况下,结果为(review_shared.contact_id = ?
为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
这是我正在使用的语句,但似乎不起作用:
$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 = ?
";
答案 0 :(得分:1)
您在联系人加入时出错:
$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 = ?
";
答案 1 :(得分:0)
或者,您也可以尝试一个equiJoin:
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 = ?