Search query for multiple column with comma separated string - search

$category_string="244,46,45";
I want query that will return product id only 239.
when i am trying to search by select * from category where category in($category_string) then it will give me all rows.
<table>
<tr><td>category_id</td><td>product_id</td></tr>
<tr><td>244</td><td>239</td></tr>
<tr><td>46</td><td>239</td></tr>
<tr><td>45</td><td>239</td></tr>
<tr><td>45</td><td>240</td></tr>
<tr><td>46</td><td>240</td></tr>
<tr><td>45</td><td>241</td></tr>
<tr><td>46</td><td>241</td></tr>
<tr><td>45</td><td>242</td></tr>
<tr><td>46</td><td>242</td></tr>
</tr>
<table>

If you want only 239
SELECT * FROM category WHERE product_id IN ( 239 );
OR
SELECT * FROM category WHERE product_id = 239;
Since you are comparing for only one product_id, i would suggest 2 query.

Related

Python SQLite 3 query multiple query

I've a problem to in building a query for Python SQLite3 to do the following:
Count a word which appears in columns, if word appears more than 1 time count one.
I've attached a picture to illustrate my table format.
I tried this but the result still counts duplicate values with same ID.
"SELECT id, value, count(value) FROM table WHERE type like'%hi%' GROUP BY value ORDER BY COUNT(*)<1 DESC"
The result needs to be like:
Hi all you need can be achieved with GROUP BY clause.
This should help:
SELECT
id
,value
,1 AS cnt
FROM table
GROUP BY id, value
ORDER BY id
What you're looking for is DISTINCT clause or GROUP BY as mentioned by Peter.
for GROUP BY use this syntax:
SELECT
id
,value
,1 AS cnt
FROM table
GROUP BY id, value
for DISTINCT use this one:
SELECT DISTINCT
id
,value
,1 AS cnt
FROM table

SQL - Insert a row into table only if not exists and count is less than a threshold

Other similar questions deal these two problems separately, but I want to merge them in a single statement. I'm using Python3 with psycopg2 library on a PostgreSQL database.
I have a table with 3 fields: ID, name, bool (BIT)
I want to insert a row in this table only if does not exists an other row with same 'name' and 'bool' = 0 and the total count of rows with same ID is less than a given threshold.
More specific my table should contain at most a given threshold number of rows with same ID. Those rows can have the same 'name', but only one of those rows with same ID and same 'name' can have 'bool'= 0.
I tried with this:
INSERT INTO table
SELECT 12345, abcdf , 0 FROM table
WHERE NOT EXISTS(
SELECT * FROM table
WHERE ID = 12345 AND name = abcdf AND bool = 0)
HAVING (SELECT count(*) FROM table
WHERE ID = 12345) < threshold
RETURNING ID;
but the row is inserted anyway.
Then I tried the same statement replacing 'HAVING' with 'AND', but it insert all the threshold rows together.

How to find colon separated values from another Table in oracle sql query where clause

I want to return row value from a Table where another table contain Colon separated value.
Suppose
I have a Table name "Unit Name" that Contain unit_id, unit_name
and Table 2 is User_reg where contain User_id. user Id contain colon separator value. Like as 82:81:80
How can get unit name list from unit_name Table
SELECT
*
FROM
unit_name un
WHERE (select school from user_reg where user_mode = 4) is not null
and un.unit_id in
(SELECT regexp_substr( school, '[^:]+', 1, LEVEL ) FROM USER_REG
CONNECT BY regexp_substr( school, '[^:]+', 1, LEVEL ) IS NOT NULL );
If you run the following query, you'll have a delimited string converted to rows.
select * from table(apex_string.split('82:81:80',':'))

Group in ranges values extracted from an 'alphanumeric + symbols' string [PostgreSQL]

Nb. I am using PostgreSQL.
Nb1. For simplicity purposes I am only showing the two relevant columns for this post, original table has more rows & columns.
I have a table called 'contents' like this:
<!DOCTYPE html>
<html>
<body>
<table border="1" style="width:100%">
<tr>
<td>id</td>
<td>data</td>
</tr>
<tr>
<td>4009</td>
<td>"duration"=>"101", "preview_version"=>"", "twitter_profile"=>"", "creator_category"=>"association", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "content_expertise_type"=>"image", "content_expertise_categories"=>"1,2,3"</td>
</tr>
<tr>
<td>4865</td>
<td>"duration"=>"108", "preview_version"=>"", "twitter_profile"=>"", "creator_category"=>"association", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "content_expertise_type"=>"image", "content_expertise_categories"=>"4,6"</td>
</tr>
</table>
</body>
</html>
from this table I need to extract the duration value by using this query:
select id,data->'duration' as data from contents
which gives me the below result (again, the original table will return many more entries and some values in "data" column will coincide reason why I need to group them in ranges):
+------+------+
| id | data |
+------+------+
| 4009 | 101 |
| 4865 | 108 |
+------+------+
Now that I have the 'data' values I want to tag them in different ranges
SELECT d.id,
case when d.data >= 0 and d.data< 10 then '0-9'
when d.data >= 10 and d.data< 20 then '10-19'
else '20-500' end as range
FROM (SELECT id,data->'duration' as data FROM contents) as d
But here the query returns this error:
ERROR: operator does not exist: text >= integer
LINE 3: case when d.data >= 0 and d.data< 10 then '0-9'
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
After this I was hoping to group the ranges like this:
SELECT t.range as score_range, count(*) as number_of_ocurrences
FROM
(***ABOVE QUERY THAT CURRENTLY RETURNS AN ERROR TO BE PLACED IN HERE***) as t
GROUP BY t.range
ORDER BY score_range
Any help to achieve this grouping task will be very much appreciated!
Looking forward to getting an answer! :-)
Thanks!
Json values in Postgres are always strings, it is necessary to cast. For fetching integer values from json fields there is a special operator ->>
Try to fetch duration as Integer value like
select id, data->>'duration' as data from contents
More info http://www.postgresql.org/docs/9.3/static/functions-json.html
It should work if you cast the value:
SELECT d.id,
(case when d.data >= 0 and d.data< 10 then '0-9'
when d.data >= 10 and d.data< 20 then '10-19'
else '20-500'
end) as range
FROM (SELECT id, (data->'duration')::int as data FROM contents
) d

Cassandra based Mahout user friend recommendations

I want to recommend a user , a list of users which the current user can add as friends.
I am using Cassandra and mahout. there is already a implementation of CassandraDataModel in mahout integration package. I want to use this class.
So my recommend-er class looks like follows
public class UserFriendsRecommender {
#Inject
private CassandraDataModel dataModel;
public List<RecommendedItem> recommend(Long userId, int number) throws TasteException{
UserSimilarity userSimilarity = new PearsonCorrelationSimilarity(dataModel);
// Optional:
userSimilarity.setPreferenceInferrer(new AveragingPreferenceInferrer(dataModel));
UserNeighborhood neighborhood =
new NearestNUserNeighborhood(3, userSimilarity, dataModel);
Recommender recommender = new GenericUserBasedRecommender(dataModel, neighborhood, userSimilarity);
Recommender cachingRecommender = new CachingRecommender(recommender);
List<RecommendedItem> recommendations = cachingRecommender.recommend(userId, number);
return recommendations;
}
}
CassandraDataModel has 4 column familys
static final String USERS_CF = "users";
static final String ITEMS_CF = "items";
static final String USER_IDS_CF = "userIDs";
static final String ITEM_IDS_CF = "itemIDs";
i have a hard time understanding this class especially the column family's. is there any example where i can look for or if someone can explain will be great with a small example.?
javadoc says this
* <p>
* First, it uses a column family called "users". This is keyed by the user ID
* as an 8-byte long. It contains a column for every preference the user
* expresses. The column name is item ID, again as an 8-byte long, and value is
* a floating point value represnted as an IEEE 32-bit floating poitn value.
* </p>
*
* <p>
* It uses an analogous column family called "items" for the same data, but
* keyed by item ID rather than user ID. In this column family, column names are
* user IDs instead.
* </p>
*
* <p>
* It uses a column family called "userIDs" as well, with an identical schema.
* It has one row under key 0. It contains a column for every user ID in the
* model. It has no values.
* </p>
*
* <p>
* Finally it also uses an analogous column family "itemIDs" containing item
* IDs.
* </p>
All the following instructions about required column families by CassandraDataMdoel should be performed in cassandra-cli under the keyspace you created (recommender or other name).
1: Table users
userID is the row key, each itemID has a separate column name, and value is the preference:
CREATE COLUMN FAMILY users
WITH comparator = LongType
AND key_validation_class=LongType
AND default_validation_class=FloatType;
Insert values:
set users[0][0]='1.0';
set users[1][0]='3.0';
set users[2][2]='1.0';
2: Table items
itemID is the row key, each userID has a separate column name, and value is the preference:
CREATE COLUMN FAMILY items
WITH comparator = LongType
AND key_validation_class=LongType
AND default_validation_class=FloatType;
Insert Values:
set items[0][0]='1.0';
set items[0][1]='3.0';
set items[2][2]='1.0';
3: Table userIDs
This table just has one row, but many columns, i.e. each userID has a separate column:
CREATE COLUMN FAMILY userIDs
WITH comparator = LongType
AND key_validation_class=LongType;
Insert Values:
set userIDs[0][0]='';
set userIDs[0][1]='';
set userIDs[0][2]='';
4: Table itemIDs:
This table just has one row, but many columns, i.e. each itemID has a separate column:
CREATE COLUMN FAMILY itemIDs
WITH comparator = LongType
AND key_validation_class=LongType;
Insert Values:
set itemIDs[0][0]='';
set itemIDs[0][1]='';
set itemIDs[0][2]='';
Complementing the answer above, for Cassandra 2.0 the new syntax is the following, according that cli is deprecated.
Table users:
CREATE TABLE users (userID bigint, itemID bigint, value float, PRIMARY KEY (userID, itemID));
Table items:
CREATE TABLE items (itemID bigint, userID bigint, value float, PRIMARY KEY (itemID, userID));
Table userIDs:
CREATE TABLE userIDs (id bigint, userID bigint PRIMARY KEY(id, userID));
Table itemIDs:
CREATE TABLE itemIDs (id bigint, itemID bigint PRIMARY KEY(id, itemID));

Resources