duansao6776 2010-11-27 17:51
浏览 66
已采纳

帮助构建图片库的数据库

i have two tables,

a) albums

alt text

b)pictures

alt text

i am using the following query to select the albums.id, albums.cover_picture_id, pictures.url where albums.cover_picture_id = pictures.id, i want to perform the following

select all the values from albums, but it should also fetch the pictures.url with reference to albums.cover_picture_id

for the purpose i am using the following SELECT STATEMENT

SELECT 
albums.id,
albums.cover_picture_id,
pictures.url
FROM albums 
JOIN pictures 
ON 
(
albums.cover_picture_id = pictures.id
)

it works fine but i have a problem here, the table entity albums.cover_picture_id may contain the value 0 which does not exist in pictures.id so it will not fetch the value if it finds 0, i would want to fetch all the albums from the albums table even if it finds 0. how do i add the clause in the select statement.

thank you

  • 写回答

2条回答 默认 最新

  • dongpai9986 2010-11-27 17:55
    关注

    use LEFT JOIN like this:

    SELECT 
    albums.id,
    albums.cover_picture_id,
    pictures.url
    FROM albums 
    LEFT JOIN pictures 
    ON 
    (
    albums.cover_picture_id = pictures.id
    )
    

    Excerpt from Wikipedia:

    The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向