PHP SQL请求 - 查询2个表,用于一个查询的结果

时间:2013-06-07 10:52:27

标签: php sql

我需要查询数据库以提取特定用户喜欢的所有汽车。

我知道user_id是1

然后我有2张桌子。 1包含所有汽车... id和描述,表2包含喜欢。

Table 1 has a list if cars and these fields:

car_id
car_name,
car_description


Table 2 has what cars I like and these fields:

user_id
car_id
likes (1 or 0)

所以我只需要从表2中仅提取用户1喜欢的记录,而只需要他喜欢的记录

我需要为此做什么SQL查询?

3 个答案:

答案 0 :(得分:2)

SELECT * FROM table1 as t0
LEFT JOIN table2 as t1 on t0.car_id = t1.car_id
WHERE t1.likes = 1

答案 1 :(得分:1)

试试这个

SELECT * FROM table1 as t1 LEFT JOIN table2 as t2 on t1.car_id = t2.car_id WHERE t2.user_id = $user_id

答案 2 :(得分:0)

尝试此查询

SELECT t1.*,t2.*
FROM tbl1 t1,tbl2 t2
WHERE likes = 1 AND user_id = 1 AND t1.car_id = t2.car_id