How to clean the commets table SQL? - sql

I have a table with IDS and COMMENTS, in which people chose on a website the reason why they ended their subscription, and that data is sent to a table.
The persons can choose more reasons, but all the reasons are sent into a single row like:
id = 111 comments = I don't like the productI hate youNever expected this
Can I rearange this table to receive the following?
id= 111 / comments= I don't like the product
id= 111 / comments= I hate you
id= 11 / comments= Never expected this
Thanks for the help!

Then this may get you to where you want
$in= "I don't like the productI hate youNever expected this";
$str = preg_replace("([A-Z])", "££$0", $in);
$arr = explode("££",trim($str, '££'));
print_r($arr);
RESULT
Array
(
[0] => I don't like the product
[1] => I hate you
[2] => Never expected this
)

Related

MVC update the database based on a non primary key value

I have a database table that looks like this:
My goal is to update my "unavail" table based on the ID of either the component, part, or item depending on which one is relevant in my situation.
For example, if the partID = 43 I want to add to the 'unavail' column
I first started working on this by trying this
db.OffSiteItemDetails.Find(sod.PartID).unavail += sod.comp_returned;
(Where sod.PartId = 43)
But I quickly realized it was just checking for where the "ID" was equal to 43 which isn't what I want. After some investigation I saw people suggesting using
db.Where(x => x.non-pk == value)
So I created this
db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID);
But from here I don't know how to change my unavail table values.
This was a tough question to type so if you need more clarity just ask
foreach(var item in db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID))
{
// item.unavail = [new value]
// db.Update(item);
// ...I don't know how you update the data in your database
}
Something like that?

sqlalchemy: paginate does not return the expected number of elements

I am using flask-sqlalchemy together with a sqlite database. I try to get all votes below date1
sub_query = models.VoteList.query.filter(models.VoteList.vote_datetime < date1)
sub_query = sub_query.filter(models.VoteList.group_id == selected_group.id)
sub_query = sub_query.filter(models.VoteList.user_id == g.user.id)
sub_query = sub_query.subquery()
old_votes = models.Papers.query.join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id).paginate(1, 4, False)
where the database model for VoteList looks like this
class VoteList(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
group_id = db.Column(db.Integer, db.ForeignKey('groups.id'))
arxiv_id = db.Column(db.String(1000), db.ForeignKey('papers.arxiv_id'))
vote_datetime = db.Column(db.DateTime)
group = db.relationship("Groups", backref=db.backref('vote_list', lazy='dynamic'))
user = db.relationship("User", backref=db.backref('votes', lazy='dynamic'), foreign_keys=[user_id])
def __repr__(self):
return '<VoteList %r>' % (self.id)
I made sure that the 'old_votes' selection above has 20 elements. If I use .all() instead of .paginate() I get the expected 20 result?
Since I used a max results value of 4 in the example above I would expect that old_votes.items has 4 elements. But it has only 2? If I increase the max results value the number of elements also increases, but it is always below the max result value? Paginate seems to mess up something here?
any ideas?
thanks
carl
EDIT
I noticed that it works fine if I apply the paginate() function on add_columns(). So if I add (for no good reason) a column with
old_votes = models.Papers.query.join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id)
old_votes = old_votes.add_columns(sub_query.c.vote_datetime).paginate(page, VOTES_PER_PAGE, False)
it works fine? But since I don't need that column it would still be interesting to know what goes wrong with my example above?
Looks to me that for the 4 rows returned (and filtered) by the query, there are 4 rows representing 4 different rows of the VoteList table, but they refer/link/belong to only 2 different Papers models. When model instances are created, duplicates are filtered out, and therefore you get less rows. When you add a column from a subquery, the results are tuples of (Papers, vote_datetime), and in this case no duplicates are removed.
I encountered the same issue and I applied van's answer but it did not work. However I agree with van's explanation so I added .distinct() to the query like this:
old_votes = models.Papers.query.distinct().join(sub_query, sub_query.c.arxiv_id == models.Papers.arxiv_id).paginate(1, 4, False)
It worked as I expected.

How to order by largest amount of identical entries with Rails?

I have a survey where users can post answers and since the answers are being saved in the db as a foreign key for each question, I'd like to know which answer got the highest rating.
So if the DB looks somewhat like this:
answer_id
1
1
2
how can I find that the answer with an id of 1 was selected more times than the one with an id of 2 ?
EDIT
So far I've done this:
#question = AnswerContainer.where(user_id: params[:user_id]) which lists the things a given user has voted for, but, obviously, that's not what I need.
you could try:
YourModel.group(:answer_id).count
for your example return something like: {1 => 2, 2 => 1}
You can do group by and then sort
Select answer_id, count(*) as maxsel
From poll
Group by answer_id
Order by maxsel desc
As stated in rails documentation (http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html) when you use group with count, active record "returns a Hash whose keys represent the aggregated column, and the values are the respective amounts"
Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }

Active Record query to match every subset element

In my RoR application, I've got a database lookup similar to this one:
Client.joins(:products).where({'product.id' => [1,2,3]})
Unfortunately this will return all clients that have bought product 1, 2 or 3 but I only want to get back the clients, that bought all of the three products. In other words, I'd like to write a query that matches for n elements in a given set.
Are there any elegant solutions for this?
This is not really elegant. But it should translate into the needed SQL.
Client.joins(:products).
where({'products.id' => [1,2,3]}).
group('users.id').
having('COUNT(DISTINCT products.id) >= 3')
Same answer with more dynamic way
ids = [1,2,3]
Client.joins(:products).
where({'products.id' => ids}).
group('users.id').
having('COUNT(DISTINCT products.id) >= ?', ids.size)

ActiveRecord: How do I find records by all of their associated records?

With ActiveRecord you can pass a field and an array into WHERE like so:
Product.joins(:category).where('category.id' => [x,y,z])
(in this case Product has a many to many relationship with Category)
This uses the IN operator to find all products in categories with an ID of x, y, or z
What I would like to do is find all products in categories with an ID of x, y, AND z. I know you can produce this sort of result like so:
Product.joins(:category).where('category.id' => x).where('category.id' => y).where('category.id' => z)
In other words, I want to find products that have all of the categories supplied.
I feel like I could do be doing something much simpler here. Any ideas?
Update: I believe this question is relevant, still having trouble getting it to work. Still think there might be another way to do this.
Havent tried... but something like below should give you hint to get started -
Product.joins(:categories).select("products.*, GROUP_CONCAT('categories.id') as category_ids").group('products.id').having('category_ids = ?', [1,2,3])
How about this:
Product.joins(:category)
.where('category.id = ? AND category.id = ? AND category.id = ?',x,y,z)