简体   繁体   English

连接的mysql查询结果问题

[英]mysql query result issue with join

I have multiple tables as table_1 has id , p_code, profile_status, name and table_2 has id, p_code, availablity and table_3 has id, p_code, status... How to get all records form all tables depend on p_code.我有多个表,因为 table_1 有 id、p_code、profile_status、name 和 table_2 有 id、p_code、availability,table_3 有 id、p_code、status...如何从所有表中获取所有记录取决于 p_code。 table_2 and table_3 has few records. table_2 和 table_3 的记录很少。 if p_code not in table_2 and table_3 then echo 'no' in results.如果 p_code 不在 table_2 和 table_3 中,则在结果中回显“no”。 currently i am using my query as below目前我正在使用我的查询如下

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 

How to add table_2 and table_3 and fetch results.如何添加 table_2 和 table_3 并获取结果。 Pleasr reply soon.请尽快回复。 I am stuck here.我被困在这里。

In your query you are doing CROSS JOIN and what you desire, is probably INNER JOIN .在您的查询中,您正在执行CROSS JOIN并且您想要的可能是INNER JOIN

In MySQL the CROSS JOIN behaves like JOIN and INNER JOIN of without using any condition.在 MySQL 中, CROSS JOIN行为类似于JOININNER JOIN的不使用任何条件。 The CROSS JOIN returns all rows form user multiplied by all rows from user_inbox - for every user you get inboxes of all users. CROSS JOIN返回来自user的所有行乘以来自user_inbox的所有行 - 对于每个用户,您获得所有用户的收件箱。

You should specify condition for your JOIN statement.您应该为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'");

Also it is good habit have the same names for primary and foreign keys, so I think you should have user_id or user_id_to instead of to_id in your user_inbox table.此外,它是很好的习惯有主键和外键相同的名称,所以我想你应该有user_iduser_id_to代替to_iduser_inbox表。 This is of course not absolutely necessary.这当然不是绝对必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM