douzha8489 2010-09-02 17:23
浏览 14
已采纳

简单的MySQL查询问题 - 获取相关记录,同时获取与之无关的记录

Hey, I think I'm going about this the wrong way, but have tried many ways, none of which give me the desired results.

Basically I have one search field which is to check multiple tables. My issue is that when, say, an item doesn't have a related person, it won't return a result for that item. Other than that it is fine. I realize the problem is in the WHERE, demanding that it find only records that match in the other table, but I'm not sure how to rectify this.

Thanks!

$q = "SELECT DISTINCT item.*
            FROM item, item_people, people
            WHERE item.record_id = item_people.item_id AND people.record_id = item_people.people_id
            AND
            item.live = '1' 
            AND
            (concat_ws(' ',people.name_first,people.name) LIKE '%$search_param%' OR
            item.name_title LIKE '%$search_param%' OR
            item.city = '$search_param' OR 
            item.category LIKE '%$search_param%' OR
            item.on_lists LIKE '%$search_param%')
            $limit";
  • 写回答

1条回答 默认 最新

  • dongyihang3575 2010-09-02 17:30
    关注

    You would need an OUTER JOIN to return items without related people.

    SELECT DISTINCT item.* /*But don't use *!
                            */
    FROM item
        LEFT OUTER JOIN item_people
        ON  item.record_id = item_people.item_id
        LEFT OUTER JOIN people
        ON  people.record_id = item_people.people_id
    WHERE item.live = '1'
    AND
        (
            concat_ws(' ',people.name_first,people.name) LIKE '%$search_param%'
        OR  item.name_title LIKE '%$search_param%'
        OR  item.city = '$search_param'
        OR  item.category LIKE '%$search_param%'
        OR  item.on_lists LIKE '%$search_param%'
        )
        $limit
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条