如果满足条件,则LEFT JOIN否则继续选择其他条件

时间:2013-06-16 03:12:08

标签: mysql relational-database

我已经四处寻找适合我所寻找的东西。我绝不接近SQL专家,所以我在这里问。我想抓住a和b,不管c是否存在,但如果c确实存在,请将LEFT JOIN加入返回。以下是我目前正在处理的声明:

SELECT a.display_name, a.first_name, a.last_name, a.profile_image, a.tagline,
       a.bragging_rights, a.about_me, b.type AS post_type, b.title AS post_title,
       b.published AS post_published, b.updated AS post_updated,
       b.content AS post_content, b.num_replies AS post_replies, 
       b.num_plus_ones AS post_plus_ones, b.num_reshares AS post_reshares,
       c.display_name AS attach_display_name, c.content AS attach_content,
       c.url AS attach_url, c.image_url AS attach_image,
       c.image_width AS attach_width, c.image_height AS attach_height,
       c.full_image_url AS attach_full_image
  FROM cr_google_profiles a
  JOIN cr_google_posts b
  LEFT JOIN cr_google_post_attachements c 
    ON b.post_id = c.post_id
 WHERE a.google_id = :google_id AND b.google_id = :google_id AND c.google_id = :google_id

我真的迷失了如何做到这一点;我一直在YouTubing和阅读手册,但没有想出任何可以实现我正在寻找的东西。任何帮助或建设性的批评都非常受欢迎。

2 个答案:

答案 0 :(得分:1)

您是否在寻找正确JOIN表格的方法?像这样的东西

SELECT ...
  FROM cr_google_profiles a JOIN cr_google_posts b 
    ON a.google_id = b.google_id LEFT JOIN cr_google_post_attachements c 
    ON b.google_id = c.google_id AND b.post_id = c.post_id 
WHERE a.google_id = :google_id 

答案 1 :(得分:0)

我认为您的问题是您没有为ab的加入指定加入条件,因此您确实需要以下内容:

SELECT a.display_name, a.first_name, a.last_name, a.profile_image, a.tagline,
       a.bragging_rights, a.about_me, b.type AS post_type, b.title AS post_title,
       b.published AS post_published, b.updated AS post_updated,
       b.content AS post_content, b.num_replies AS post_replies, 
       b.num_plus_ones AS post_plus_ones, b.num_reshares AS post_reshares,
       c.display_name AS attach_display_name, c.content AS attach_content,
       c.url AS attach_url, c.image_url AS attach_image,
       c.image_width AS attach_width, c.image_height AS attach_height,
       c.full_image_url AS attach_full_image
  FROM cr_google_profiles a
  JOIN cr_google_posts b
    ON a.google_id = b.google_id
  LEFT JOIN cr_google_post_attachements c 
    ON b.post_id = c.post_id
 WHERE a.google_id = :google_id
   AND b.google_id = :google_id
   AND c.google_id = :google_id