如何按条件在查询中加入新列?我有 3 张 table :
Users table:
userid name
1 John
2 Joe
3 Sam
4 Alex
Questions table:
userid questionid asked
1 1 2011-11-11 22:52
1 2 2011-11-11 22:52
3 3 2011-11-11 22:52
2 4 2011-11-11 22:52
Like table:
userid questionid
1 1
1 2
1 3
1 4
我想查询用户的问题并确定用户是否喜欢该问题。结果应该是用户是否喜欢这个问题:
userid questionid liked
1 1 1
用户不喜欢该问题的其他情况:
userid questionid liked
2 1 0
我现在使用的具体代码:(有点不同的字段名称)
SELECT temp.`id`, temp.`userid`, `categories`.`name`, `user`.`username`, temp.`title`,
temp.`details`, temp.`date` FROM (
SELECT `id`, `categoryid`, `details`, `title`, `userid`, `date`, @a := id, if(@a = ". $position .", @b := 1, @b) AS join_id
FROM `questions`
join(SELECT @a := 0, @b := 0) t
ORDER BY `date` DESC
) as temp
LEFT JOIN `user`
ON temp.`userid` = `user`.`userid`
LEFT JOIN `categories`
ON temp.`categoryid` = `categories`.`categoryid`
WHERE join_id = 1
LIMIT 1,5;
Position 表示要查询的 id。 ATM 用户 ID 31 仅喜欢问题。 SQLfiddle:http://sqlfiddle.com/#!2/5fe17/2
最佳答案
使用左(外)连接将 Like
表连接到 Question
表。
对于每个匹配,Like.userid
(和 Like.questionid
)将为 not null
,否则为 null
。
您可以使用 IF()
函数在选择列中检查这一点:
SELECT userid, questionid, if(Questions.userid is null, 0, 1) as liked
FROM Questions
LEFT OUTER JOIN Like ON Questions.userid = Like.userid and Questions.questionid = Like.questionid;
这列出了用户被问到的所有问题。您可以通过添加 WHERE
子句将范围缩小到一名用户和一个问题。
(请注意,LIKE 是 MySQL 中的关键字。您应该选择其他表名或在语句中引用/转义表名)。
关于mysql - 按条件加入新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714436/