我想创建一个临时表,其中包含某些页面中某些单词的位置分数。
在sqlite中,我有2个表格,页面和字位置:
pages
-------
|url|
|example.com|
|example2.com|
|example3.com|
和:
wordlocations
-------
| url |wordid|location|
|example.com | 1| 2|
|example.com | 1| 35|
|example.com2| 1| 0|
|example.com2| 1| 75|
|example.com3| 2| 75|
我想创建一个包含url,最低位置分数的表,如果单词不存在=>,请将位置分数设置为10000。因此在下面的示例中,当我想为wordid = 1
,我希望它看起来像:
result
-------
| url |min(location)|
|example.com | 2|
|example2.com| 0|
|example3.com| 100000|
我尝试过
CREATE TEMPORARY TABLE result AS SELECT url, IFNULL(MIN(location), 100000) FROM wordlocation WHERE wordid = 1 GROUP BY url;
但是那遗漏了没有wordid的页面,即
result
-------
| url |min(location)|
|example.com | 2|
|example2.com| 0|
我将如何检索这样一个表,该表包含位置得分最低的所有页面,并且仍然保留不包含默认值的wordid的页面?
答案 0 :(得分:1)
选中使用UNION
合并这两种情况的选项:
CREATE TEMPORARY TABLE result AS
SELECT url, MIN(location) AS minlocation
FROM wordlocations
WHERE wordid = 1
GROUP BY url
UNION
SELECT url, 100000 AS minlocation
FROM wordlocations
WHERE wordid <> 1
GROUP BY url;
编辑,第二版:
CREATE TEMPORARY TABLE result AS
SELECT url, MIN(location) AS minlocation
FROM wordlocations
WHERE wordid = 1
GROUP BY url
UNION
SELECT url, 100000 AS minlocation
FROM wordlocations
WHERE url NOT IN (SELECT DISTINCT url FROM wordlocations WHERE wordid = 1)
GROUP BY url;