MySQL SELECT查询选择中的where子句

时间:2014-08-14 15:24:14

标签: mysql

SELECT *, j.company_id as companyid, j.id as jid, p.id as pid, f.id as fave_id, f.user_id as user_id
FROM people p
LEFT JOIN job j 
ON p.job_id = j.id
LEFT JOIN favourites f
ON p.id = f.people_id
WHERE p.company_id = 1
ORDER BY p.id ASC

我有上面的MySQL查询工作正常,最后两个选项是我需要解决的问题。

默认情况下,每行输出null,否则会输出fave_id46user_id的整数为6

我真正需要弄清楚的是,如果fave_iduser_id在我的头脑中都不是空的话,是否可以从查询的SELECT部分​​输出这样的事情

SELECT *, j.company_id as companyid, j.id as jid, p.id as pid, f.id as fave_id, f.user_id as user_id, [if fave_id && user_id then favorite = true] 
FROM people p
LEFT JOIN job j 
ON p.job_id = j.id
LEFT JOIN favourites f
ON p.id = f.people_id
WHERE p.company_id = 1
ORDER BY p.id ASC

2 个答案:

答案 0 :(得分:2)

CASE语句可以检查值并返回所需的值:

SELECT *, j.company_id as companyid, j.id as jid, p.id as pid, f.id as fave_id, f.user_id as user_id, 
    (CASE WHEN fave_id IS NOT NULL AND user_id IS NOT NULL THEN 1 ELSE 0 END) AS favorite 
FROM people p
LEFT JOIN job j 
ON p.job_id = j.id
LEFT JOIN favourites f
ON p.id = f.people_id
WHERE p.company_id = 1
ORDER BY p.id ASC

答案 1 :(得分:0)

使用and

fave_id is not null and user_id is not null