我有这两个表:如何为每个帖子选择作者的姓名?
// posts
+----+---------+------------------------+-----------+------------+
| id | title | content | author_id | visibility |
+----+---------+------------------------+-----------+------------+
| 1 | title1 | content1 | 3 | 1 |
| 2 | title2 | content2 | 2 | 0 |
+----+---------+------------------------+-----------+------------+
// users
+----+---------+----------+
| id | fname | lname |
+----+---------+----------+
| 1 | John | Tersco |
| 2 | Peter | Brlew |
| 3 | Jack | Keveinc |
+----+---------+----------+
我想这是预期输出:
+----+---------+------------------------+--------------+
| id | title | content | full_name |
+----+---------+------------------------+--------------+
| 1 | title1 | content1 | Jack Keveinc |
| 2 | title2 | content2 | Unknown |
+----+---------+------------------------+--------------+
这里是我当前的查询:
SELECT p.id, p.title, p.content, CONCAT(u.fname, ' ', u.lname) as full_name
FROM posts p
LEFT JOIN users u
ON p.author_id = u.id AND p.visibility = 1
正如你看到的,我需要的是定义当p.visibility
等于0
时为。我怎样才能做到这一点?
我需要CASE
或COALESCE
或两者吗?
编辑:首先我要说的添Biegeleisen的答案是伟大的,所有的罚款。实际上,还有一列我需要像上面那样对待它。但它没有CONCAT
功能。例如:
// users
+----+---------+----------+------------+
| id | fname | lname | reputation |
+----+---------+----------+------------+
| 1 | John | Tersco | 943 |
| 2 | Peter | Brlew | 2300 |
| 3 | Jack | Keveinc | 84 |
+----+---------+----------+------------+
这是预期的结果:
+----+---------+------------------------+--------------+------------+
| id | title | content | full_name | reputation |
+----+---------+------------------------+--------------+------------+
| 1 | title1 | content1 | Jack Keveinc | 84 |
| 2 | title2 | content2 | Unknown | N |
+----+---------+------------------------+--------------+------------+
好吧,我只想知道:还有我可以用COALESCE
为reputation
列? (它没有CONCAT
)
SELECT COALESECE(reputation, 'N') reputation, ....
它是罚款?或者因为它没有CONCAT
那么我必须使用CASE
呢?
最好的答案,这是最好的有'p.visibility = 1'在加入本身,所以你不包括所有行'p.visibility = 0' – DerpyNerd
如果我删除CASE,会发生什么情况?我想这是多余的。我的意思是使用COALESCE就够了,不是吗? –
@MartinAJ你说得对,'COALESCE'就够了。 –