1

我有如下表格:

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列在两个表中都很常见。我想要做的,左加入两个表与字段值(空或不)

THE RESULT SHOULD BE (IF DNR_ID = 1) :
+-------------+---------+
| DESCRIPTION | CHECKED |
+-------------+---------+
|    DESC A   |    1    |
+-------------+---------+
|    DESC B   |    1    |
+-------------+---------+
|    DESC C   |    0    |
+-------------+---------+
4

5 回答 5

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 
于 2013-12-25T08:25:47.530 回答
1

尝试使用FIND_IN_SET()

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

SQLFiddle demo

于 2013-12-25T08:25:58.890 回答
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) 

sqlfiddle 上的演示

于 2013-12-25T08:33:44.173 回答
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)
于 2013-12-25T09:46:33.557 回答
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)
于 2013-12-25T10:11:52.940 回答