你可以爲這種性質的給定數據集做這樣的事情:
create table items (
user_id int,
item_id int,
item_property text
);
create table liked (
user_id int,
item_id int
);
insert into items values
(1, 1, 'Ball'), (1, 2, 'Bat'), (1, 3, 'Glove'),
(2, 4, 'Jar'), (2, 5, 'Cooker'), (2, 6, 'Stove'),
(3, 7, 'Ram'), (3, 8, 'CPU'), (3, 9, 'SSD');
insert into liked values
(1, 2), (2, 6), (3, 7);
查詢
select i.*, case when l.user_id is null then 0 else 1 end as liked
from items i
left join liked l
on i.user_id = l.user_id
and i.item_id = l.item_id
結果
| user_id | item_id | item_property | liked |
|---------|---------|---------------|-------|
| 1 | 2 | Bat | 1 |
| 2 | 6 | Stove | 1 |
| 3 | 7 | Ram | 1 |
| 1 | 1 | Ball | 0 |
| 1 | 3 | Glove | 0 |
| 2 | 4 | Jar | 0 |
| 2 | 5 | Cooker | 0 |
| 3 | 8 | CPU | 0 |
| 3 | 9 | SSD | 0 |
推薦
不要使用附加列創建新表。只需運行適當的SQL查詢以獲取您喜歡的表中的實際字段以及其他派生/計算字段。
爲了模擬一個表,你可以創建這樣一個觀點:
create view items_liked
as
select i.*, case when l.user_id is null then 0 else 1 end as liked
from items i
left join liked l
on i.user_id = l.user_id
and i.item_id = l.item_id;
這樣,你總是可以運行select * from items_liked
並獲取你想要的數據,而無需創建一個表。
示例可在此處獲得:http://sqlfiddle.com/#!9/8a4ef/1