dongmu5596 2014-08-15 09:18
浏览 43
已采纳

MySQL高级选择查询检查来自另一个表的数据

I have a Database that I'm struggling to do a query for. The main table is people and what I am trying to do is add onto the end of the select query the id from the favourites table ONLY if the client_member_id matches.

The idea is to loop through each People row and at the end of the row add on the f.id if that persons id is in the favourites table AND it matches the id of the client_member_id.

The client_member_id is an id given to each client so that when they Favourite a person then the details get put to the favourites table. This would be either 1 or 2. In the SQLFiddle example the expected output of the FAVE_ID when client_member_id is 2 would be 68 69 but if client_member_id is 1 then FAVE_ID would both be null

I have gotten it to a point where it seems to duplicate the rows and I need it to be distinct.

SELECT *, j.company_id as companyid, j.id as jid, p.id as pid,
    (CASE WHEN f.client_member_id = 2 AND p.id = f.people_id THEN f.id ELSE null END) AS fave_id,
    (CASE WHEN f.client_member_id = 2 AND p.id = f.people_id THEN 1 ELSE 0 END) AS fave
FROM people p
INNER JOIN favourites f
INNER JOIN job j 
ON p.job_id = j.id
WHERE p.company_id = 1
ORDER BY p.id ASC

SQLFiddle

Thank you in advance.

  • 写回答

3条回答 默认 最新

  • douyeke2695 2014-08-15 09:43
    关注

    You can use a LEFT JOIN to favourites to get rid of the ungainly CASE:

        SELECT *,
               j.company_id companyid,
               j.id jid,
               p.id pid,
               f.id fave_id,
               f.id IS NOT NULL fave
          FROM people p    
    INNER JOIN job j 
            ON p.job_id = j.id
     LEFT JOIN favourites f
            ON f.people_id=p.id
           AND f.client_member_id=2
         WHERE p.company_id = 1
      ORDER BY p.id ASC
    

    N.B This will return only two rows for your fiddle with fave_id and fave, NOT NULL and 1, but in the event that you have a person without a corresponding favourite then you get fave_id and fave, NULL and 0.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题