我有如下表格:
TABLE A
+-----+---------------+-------------+
| ID | DNR_DETAIL_ID | DESCRIPTION |
+-----+---------------+-------------+
| 1 | 1 | DESC A |
+-----+---------------+-------------+
| 2 | 2 | DESC B |
+-----+---------------+-------------+
| 3 | 3 | DESC C |
+-----+---------------+-------------+
TABLE B
+--------+---------------+
| DNR_ID | DNR_DETAIL_ID |
+------------------------+
| 1 | 1,2 |
+--------+---------------+
| 2 | 3 |
+--------+---------------+
如您所见,DNR_DETAIL_ID
列在两个表中都很常见。我想做什么,将两个表连接到字段值(null或不是)
THE RESULT SHOULD BE (IF DNR_ID = 1) :
+-------------+---------+
| DESCRIPTION | CHECKED |
+-------------+---------+
| DESC A | 1 |
+-------------+---------+
| DESC B | 1 |
+-------------+---------+
| DESC C | 0 |
+-------------+---------+
答案 0 :(得分:1)
试试这个:
SELECT TA.description AS DESCRIPTION, CASE WHEN TB.checked IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM
(
select distinct description from TableA
) TA left join
(
SELECT description, 'checked' FROM TableA where dnt_detail_id in (
select dnr_detail_id from TableB where dnr_id = 1
)
)TB ON TB.description = TA.description
答案 1 :(得分:1)
SELECT
A.Description,
CASE WHEN B.DNR_ID IS NOT NULL THEN 1 ELSE 0 END as Checked
FROM A
LEFT JOIN B
ON FIND_IN_SET(A.DNR_DETAIL_ID, B.DNR_DETAIL_ID)
AND B.DNR_ID=1
答案 2 :(得分:1)
SELECT a.DESCRIPTION,
CASE WHEN b.DNR_ID IS NOT NULL THEN 0 ELSE 1 END as CHECKED
FROM table_a a
LEFT JOIN table_b b
ON FIND_IN_SET(a.DNR_DETAIL_ID, b.DNR_DETAIL_ID)
答案 3 :(得分:1)
非常感谢你们。我已经尝试了你所有的建议,但没有一个能起作用。有趣的是,代码在sqlfiddle
(相同的模式和值)中运行良好,但在本地环境中无效!这是在本地工作的查询。
/**
* DNR_DETAIL_DESC IS TABLE A
* DNR_LIST IS TABLE B
*/
SELECT A.DNR_DETAIL_DESC,
CASE WHEN B.DNR_ID IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM MD_DNR_DETAIL A
LEFT JOIN (SELECT * FROM DNR_LIST WHERE DNR_ID = 1) AS B
ON FIND_IN_SET(A.DNR_DETAILT_ID, B.DNR_DETAIL_ID)
答案 4 :(得分:0)
你可以用很多方式写出来,但这是最好的方法:
SELECT
MD_DNR_DETAIL.DNR_DETAIL_DESC as DESCRIPTION,
CASE WHEN DNR_LIST.DNR_ID IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM MD_DNR_DETAIL
LEFT JOIN DNR_LIST
ON FIND_IN_SET(MD_DNR_DETAIL.DNR_DETAILT_ID, DNR_LIST.DNR_DETAIL_ID)