CASE 和 IF 查询只返回一个条件结果
CASE and IF query only returning one conditional result
SELECT a.*, IF(b.pid=a.id,b.id,0) AS bpid
FROM table1 a, table2 b
ORDER BY a.datetime DESC;
我在 table1 a 中有十五条记录,在 table2 b 中有两条记录,其中 b.pid=a.id
.
在任何给定时间,只有来自 table b 的记录之一被拉入结果。两者都应该作为 bpid 被拉入,但只有两者中的后者才能成功。
我也尝试过使用 CASE
(实际上是先尝试 CASE
):
SELECT a.*, (CASE WHEN b.pid=a.id THEN b.id ELSE NULL END) AS bpid
FROM table1 a, table2 b
ORDER BY a.datetime DESC;
我错过了什么?
为清楚起见:我在结果中得到了 table1 a 中的所有 15 条记录,但没有从 table2 b.
中得到两条记录
您没有正确加入表格。作为提示,停止在 FROM 子句中使用逗号,这将帮助您考虑连接应该是什么。
/* for all records */
SELECT
a.*
, b.id AS bpid
FROM table1 a
LEFT JOIN table2 b ON a.id = b.id
ORDER BY a.DATETIME DESC
或
/* for only matching records */
SELECT
a.*
, b.id AS bpid
FROM table1 a
INNER JOIN table2 b ON a.id = b.id
ORDER BY a.DATETIME DESC
SELECT a.*, IF(b.pid=a.id,b.id,0) AS bpid
FROM table1 a, table2 b
ORDER BY a.datetime DESC;
我在 table1 a 中有十五条记录,在 table2 b 中有两条记录,其中 b.pid=a.id
.
在任何给定时间,只有来自 table b 的记录之一被拉入结果。两者都应该作为 bpid 被拉入,但只有两者中的后者才能成功。
我也尝试过使用 CASE
(实际上是先尝试 CASE
):
SELECT a.*, (CASE WHEN b.pid=a.id THEN b.id ELSE NULL END) AS bpid
FROM table1 a, table2 b
ORDER BY a.datetime DESC;
我错过了什么?
为清楚起见:我在结果中得到了 table1 a 中的所有 15 条记录,但没有从 table2 b.
中得到两条记录您没有正确加入表格。作为提示,停止在 FROM 子句中使用逗号,这将帮助您考虑连接应该是什么。
/* for all records */
SELECT
a.*
, b.id AS bpid
FROM table1 a
LEFT JOIN table2 b ON a.id = b.id
ORDER BY a.DATETIME DESC
或
/* for only matching records */
SELECT
a.*
, b.id AS bpid
FROM table1 a
INNER JOIN table2 b ON a.id = b.id
ORDER BY a.DATETIME DESC