我有多个表,因为table_1有id、p_code、profile_status、名称,table_2有id、p_code、可用性,table_3有id、p_code、状态... 如何获取所有表的所有记录取决于p_code。 table_2和table_3的记录很少。如果 p_code 不在 table_2 和 table_3 中,则在结果中回显“no”。 目前我正在使用我的查询如下
select t.id, t.p_code,t.name,t.num_rooms, t.profile_status, t.distance FROM (
( SELECT id , p_code, profile_status, name,num_rooms, 3956 * 2 * ASIN(SQRT( POWER(SIN(($origLatAirport - latitude)*pi()/180/2),2)
+COS($origLatAirport*pi()/180 )*COS(latitude*pi()/180)
*POWER(SIN(($origLonAirport-longitude)*pi()/180/2),2)))
as distance FROM property WHERE profile_status=1 having distance < ".$dist." ) ) as t
如何添加table_2和table_3并获取结果。 请尽快回复。我被困在这里了。
最佳答案
在您的查询中,您正在执行CROSS JOIN
,而您想要的可能是INNER JOIN
。
在 MySQL 中,CROSS JOIN
的行为类似于 JOIN
和 INNER JOIN
,但不使用任何条件。
CROSS JOIN
返回 user
中的所有行乘以 user_inbox
中的所有行 - 对于每个用户,您都会获得所有用户的收件箱。
您应该为 JOIN
语句指定条件。
$sql_alt = mysql_query(
"select i.*,u.images, u.firstname, u.lastname
from user_inbox i INNER JOIN user u ON i.to_id = u.user_id
where i.to_id = '$user_id'");
另外,主键和外键的名称相同是个好习惯,所以我认为您应该使用 user_id
或 user_id_to
而不是 to_id
在您的 user_inbox
表中。这当然不是绝对必要的。
关于mysql 查询结果与 join 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25579355/