我有一个数据库,我正在努力进行查询。主表格为people
,如果add
,{I} id
仅在favourites
的{{1}}结尾处client_member_id
}匹配。
这个想法是循环遍历每个People
行,如果那个人ID在f.id
表中并且它与{{favourites
匹配,则在id
的行末尾添加client_member_id
1 {} client_member_id
。
1
是给每个客户的ID,这样当他们最喜欢一个人时,细节就会被放到收藏夹表中。这可以是2
或FAVE_ID
。在SQLFiddle示例中,client_member_id
为2
时68
的预期输出为69
client_member_id
,但如果1
为FAVE_ID
然后null
都是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
我已经把它弄到了似乎复制行的地步,我需要它是截然不同的。
{{1}}
提前谢谢。
答案 0 :(得分:1)
没有重复项,因为fave_id和fave列,你有4行。如果你想过滤它们,那么这里是一个如何只显示fave = 1的值的例子:
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 AND f.client_member_id = 2 AND p.id = f.people_id
ORDER BY p.id ASC
答案 1 :(得分:1)
您可以使用LEFT JOIN加入收藏夹以摆脱笨拙的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
NB 这将为您的小提琴只返回两行fave_id
和fave
,NOT NULL和1,但如果您有一个没有相应的人最喜欢的是你得到fave_id
和fave
,NULL和0。
答案 2 :(得分:0)
试试这个SQLFiddle
SELECT *, j.company_id as companyid, j.id as jid, p.id as pid,
(CASE WHEN f.client_member_id = 2 THEN f.id ELSE null END) AS fave_id,
(CASE WHEN f.client_member_id = 2 THEN 1 ELSE 0 END) AS fave
FROM people p
INNER JOIN job j ON p.job_id = j.id
left JOIN favourites f on f.people_id = p.id
WHERE p.company_id = 1
ORDER BY p.id ASC
您没有将您的收藏夹表连接绑定到任何内容,因此您有多少行*返回的收藏数。我使用左连接,因为我猜你不能保证人员表中的每个人都会有一个喜欢的东西?否则,如果你可以改为内连接。
此致
利安