简体   繁体   English

Mysql IF EXIST是否应用于此查询?

[英]Is Mysql IF EXIST what should be used for this query?

select social_members.* 
     , social_mcouple.* 
 WHERE m_id = '".$_SESSION['userid'] . "' 
   AND c_id = '".$_SESSION['userid'] . "'

Select all fields from social_members.* and if social_mcouple.c_id = $_SESSION['userid'] then Select all fields from social_mcouple.* as well. 从social_members。*中选择所有字段,如果social_mcouple.c_id = $ _SESSION ['userid'],则也从social_mcouple。*中选择所有字段。 Can this be done with IF EXIST and if so how. 可以使用IF EXIST来完成此操作吗? Thanks 谢谢

If I undertand you correctly, an outer join would be better here. 如果我正确地理解了您的观点,那么外部联接会更好。

SELECT social_members.*
     , social_mcouple.* 
  FROM social_members 
  LEFT OUTER JOIN social_mcouple 
    ON social_members.m_id=social_mcouple.c_id 
 WHERE m_id='".$_SESSION['userid']."'

This will retrieve rows for each member, and any corresponding rows from social_mcouple . 这将检索每个成员的行,以及来自social_mcouple的任何相应行。 If there are no corresponding rows in the social_mcouple table, then all the social_mcouple.* rows in the result will be NULL. 如果social_mcouple表中没有对应的行,那么结果中的所有social_mcouple。*行都将为NULL。

Depending upon your exact needs, and the relationship between the two tables, you may be better simply running this as two queries, one to retrieve matching rows from social_members, and the other to retrieve rows from social_mcouple. 根据您的确切需求以及两个表之间的关系,最好将其作为两个查询运行,一个查询从social_members检索匹配的行,另一个从social_mcouple检索行。 Whether you take the outer join or two separate queries will depend upon the "shape" of the data you want back. 是否进行外部联接还是两个单独的查询将取决于要返回的数据的“形状”。

And just in case, you were thinking it's not possible to return a different number of columns depending upon the data. 为了以防万一,您认为不可能根据数据返回不同数量的列。 (Eg only the social_members columns if there are no applicable social_mcouple rows.) (例如,如果没有适用的social_mcouple行,则仅显示social_members列。)

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

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