我有以下问题
SELECT * from map_user_sticker WHERE map_user_sticker.user_id = 7;
+----+---------+------------+
| id | user_id | sticker_id |
+----+---------+------------+
| 35 | 7 | 55 |
| 3 | 7 | 30 |
| 32 | 7 | 49 |
| 33 | 7 | 52 |
| 34 | 7 | 43 |
| 36 | 7 | 50 |
+----+---------+------------+
6 rows in set (0.00 sec)
SELECT * FROM sticker;
+----+--------------------------------------------------+
| id | word |
+----+--------------------------------------------------+
| 40 | I love Sonal |
| 41 | Add User to Database |
| 39 | This is a dream Project |
| 33 | Narendra Sisodiya |
| 34 | Sourabh Parmar |
| 30 | Sonal Sisodiya |
| 42 | I love India |
| 43 | I love Linux |
| 44 | I hate Congress |
| 45 | I love jQuery |
| 48 | Modi will be the PM |
| 47 | Ramdev Baba is my Super Hero |
| 49 | हिन्दी से प्यार है |
| 50 | Linux is better then Windows |
| 52 | I am from Sehore |
| 55 | I have 2 little kids - sadu and sonu |
+----+--------------------------------------------------+
16 rows in set (0.00 sec)
我基本上想要生成像
这样的结果+----+--------------------------------------------------+----------+
| id | word | present |
+----+--------------------------------------------------+----------+
| 40 | I love Sonal | 0 |
| 41 | Add User to Database | 0 |
| 39 | This is a dream Project | 0 |
| 33 | Narendra Sisodiya | 0 |
| 34 | Sourabh Parmar | 0 |
| 30 | Sonal Sisodiya | 1 |
| 42 | I love India | 0 |
| 43 | I love Linux | 1 |
| 44 | I hate Congress | 0 |
| 45 | I love jQuery | 0 |
| 48 | Modi will be the PM | 0 |
| 47 | Ramdev Baba is my Super Hero | 0 |
| 49 | हिन्दी से प्यार है | 1 |
| 50 | Linux is better then Windows | 1 |
| 52 | I am from Sehore | 1 |
| 55 | I have 2 little kids - sadu and sonu | 1 |
+----+--------------------------------------------------+----------+
16 rows in set (0.00 sec)
请帮帮我!! 我想根据以下条件生成一个名为“present”的额外列 如果来自查询2的来自query1 == id的sticker_id,则present = 1 否则出现= 0
答案 0 :(得分:3)
这里是我想要的答案!
答案1 -
SELECT s.* , IF(FIND_IN_SET(7,(GROUP_CONCAT(m.user_id))) != 0 , 1,0) as present, COUNT(m.user_id) as totalUsers
FROM sticker s
LEFT JOIN map_user_sticker m
ON s.id = m.sticker_id
GROUP BY id;
答案2 -
SELECT id,word, (case when 7 in (select user_id from map_user_sticker WHERE map_user_sticker.sticker_id=sticker.id) then 1 else 0 end) as present
from sticker;
我不知道哪一个更快更好
答案 1 :(得分:1)
试试这个:
select id,word,
case(when id in (select sticker_id from map_user_sticker) then 1 else 0 end)
as present from sticker;
答案 2 :(得分:0)
希望,这会有所帮助:
SELECT sticker.id, sticker.word, (IF(sticker_id IS NULL, 0, 1)) AS present FROM sticker LEFT JOIN map_user_sticker ON (sticker.id = map_user_sticker.sticker_id)
答案 3 :(得分:0)
尝试此查询 -
SELECT s.*, IF(COUNT(m.sticker_id) > 0, 1, 0) present FROM sticker s
LEFT JOIN map_user_sticker m
ON s.id = m.sticker_id
GROUP BY
s.id;
这是你想要的吗?
SELECT s.*, IF(m.sticker_id IS NULL, 0, 1) present FROM sticker s
LEFT JOIN map_user_sticker m
ON s.id = m.sticker_id
WHERE m.user_id = 7;