如何从具有第三个条件的两个表中进行查询


How to query from two tables with the condition of a third

我有三个表:地方用户位置图像

我需要进行一个查询,将用户喜欢的所有位置与第三个表图像中的位置图像放在一起。

现在我设法做到了:

"SELECT Location.* FROM Location LEFT JOIN UserLocation ON Location.id = UserLocation.location_id WHERE UserLocation.user_id=:user_id:

但它只检索用户喜欢的位置。现在我需要每个地方的照片。我该怎么做?

您需要将条件移动到on子句:

SELECT l.*, (ul.user_id is not null) as hasUser
FROM Location l LEFT JOIN
     UserLocation ul
     ON l.id = ul.location_id and
        ul.user_id = :user_id:

where子句以将LEFT JOIN转换为INNER JOIN的方式过滤输出。