correction for mysql query of rails - mysql

While executing the below mysql query in rails
cnt = Domainurl.find_by_sql ["SELECT Max(`count`)FROM `domainurls` WHERE `domaindetail_id`= ?",#domain.id]
urlcr=Domainurl.find_by_sql ["SELECT * FROM `domainurls` WHERE `domaindetail_id` = ? AND `count` = ?",cnt.count]
urlcr.each do |cr|
puts cr.url
end
I am getting error :
"error is: undefined method `closed?' for nil:NilClass"

the problem is at your last query
urlcr=Domainurl.find_by_sql ["SELECT * FROM `domainurls` WHERE `domaindetail_id` = ? AND `count` = ?",cnt.count]
you try to find something by 2 parameters ( domaindetail_id and count) but you provide only count. (you must provide domaindetail_id too)
urlcr=Domainurl.find_by_sql ["SELECT * FROM `domainurls` WHERE `domaindetail_id` = ? AND `count` = ?",#domain.id, cnt.count] #observe that I added #domain.id
You can rewrite that like
cnt = Domainurl.where(:domaindetail_id => #domain.id).maximum(:count) # this returns a number
urlcr=Domainurl.where("domaindetail_id = ? AND count = ?", #domain.id, cnt)

Related

Convert Sql query to sql CodeIgniter

convert sql query to sql codeigniter
i done try to use this method
How to convert sql query to codeigniter active records
but not working for me...
so i try to post in here
this my sql query
$sql = "SELECT b.id, b.us_id, b.kredit, b.info,u.us_name,
u.us_username, u.us_email, u.us_phone, b.cnt, b.amnt
FROM users u JOIN
(SELECT id, us_id, kredit, info, COUNT(info) cnt, SUM(kredit) amnt
FROM balance_history
GROUP BY info HAVING cnt > 1
) AS b
ON u.us_id = b.us_id
WHERE b.kredit != '0' AND
b.info NOT LIKE '[PERBAIKAN]%' AND
(b.info LIKE 'Transfer saldo%' OR b.info LIKE 'Ket%')
ORDER BY b.id ASC";
thanks before...
If you aren't loaded database globally, you can load it by calling $this->load->database(); The following query may provide the same db call.
$this->db->select('id, us_id, kredit, info, COUNT(info) cnt, SUM(kredit) amnt')
->from('balance_history')
->group_by('info')
->having('cnt > 1');
$subquery = $this->db->get_compiled_select();
$query = $this->db
->select('b.id, b.us_id, b.kredit, b.info,u.us_name,u.us_username, u.us_email, u.us_phone, b.cnt, b.amnt')
->from('users u')
->join('('.$subquery.') b','u.us_id = b.us_id')
->where('b.kredit !=','0', true)
->not_like('b.info', '[PERBAIKAN]', 'after', false, true)
->where('(b.info LIKE "Transfer saldo%" OR b.info LIKE "Ket%")')
->get();

SQL - How to handle two conditions without using AND?

I have this query:
String queryStr = 'SELECT COUNT(*) FROM tester x WHERE x.state !=:state'
setParameter("state", "state1");
I want to count all that are "state1" and "state2"
Is there a way to do it rather than :
String queryStr = 'SELECT COUNT(*) FROM tester x WHERE (x.state !=:state1 AND x.state !=:state2)';
setParameter("state1", "state1");
setParameter("state2", "state2");
Thanks
use not in
WHERE (x.state NOt IN (:state1,:state2))
then your whole query will be
'SELECT COUNT(*) FROM tester x WHERE (x.state NOt IN (:state1,:state2))';
Note: above solution is according to yor query, but according to your text [I want to count all that are "state1" and "state2"]
then your query can be
'SELECT COUNT(*) FROM tester x WHERE x.state = :state1 AND x.state = :state2';

How can I execute this SQL query in Drupal?

I'd like to execute the following SQL query in Drupal...but haven't had any luck.
SELECT SUM(field_count) FROM headon_entry WHERE uid = 1 AND tid = 263;
I've used the following, but with no luck:
$query = db_select('headon_entry', 'he')
->condition('uid', $uid)
->condition('tid', $product_id);
$query->addExpression('SUM(field_count)', 'field_count');
$entry_quantity = $query->execute();
Your query comes out as
SELECT SUM(field_count) AS field_count
FROM
{headon_entry} he
WHERE (uid = :db_condition_placeholder_0) AND (tid = :db_condition_placeholder_1)
So what you've got is correct as far as building the query goes.
What you haven't done is extract the result from the query execution. Try this:
$entry_quantity = $query->execute()->fetchField();

Use Multiple keywords with mysql Like

I want to write mysql query to display all records if text field value = "All" or else display records similar to keyword value. I have written code below to just to give an idea.
if (keyword = 'All' )
select * from ItemMain
else if (keyword like %itemname%)
select * from ItemMain
Ok, assuming PHP as the front-end language you can put it all in one query like this (forgive the curly braces; I'm never sure when they're needed or not so I tend to over-use them):
$query = <<< ENDSQL
SELECT *
FROM ItemMain
WHERE ('{$keyword}' = 'All') OR (your_textfield like '%{$keyword}%')
ENDSQL;
... execute the query
But really I'd go with the suggestion from #cjg and use two different queries:
$query = "";
if ($keyword == 'All') {
$query = "SELECT * FROM ItemMain";
} else {
$query = "SELECT * FROM ItemMain WHERE your_textfield LIKE '%{$keyword}%'";
}
... execute the query
If itemname is your column name, and your search string parameter replaces the ? in your code. Then your statement should look something like this if you are searching for all itemnames containing your search string:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname LIKE '%?%'
Or this if you are looking for an exact match:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname = ?

arel union and latest conversation from messages

I need a list of messages where each one is the most recent in the "conversation" between the current user and each other user.
The same query is described in this question
The code I have so far is:
t1 = Arel::Table.new(:messages, :as => 't1')
t2 = Arel::Table.new(:messages, :as => 't2')
convs1 = t1.
project(
t1[:receiver_user_id].as('other_user_id'),
t1[:receiver_user_id].as('receiver_user_id'),
t1[:sender_user_id].as('sender_user_id'),
t1[:created_at].as('created_at')
).
where(t1[:sender_user_id].eq(user.id))
convs2 = t2.project(
t2[:sender_user_id].as('other_user_id'),
t2[:receiver_user_id].as('receiver_user_id'),
t2[:sender_user_id].as('sender_user_id'),
t2[:created_at].as('created_at')
).
where(t2[:receiver_user_id].eq(user.id))
conv = convs1.union(convs2)
First off, I get an error:
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check \
the manual that corresponds to your MySQL server version for the right syntax to use near \
'UNION SELECT `t2`...
This works if I manually replace "UNION" with "UNION ALL" in the sql produced below.
conv.to_sql from the above code produces:
SELECT `t1`.`receiver_user_id` AS other_user_id,
`t1`.`receiver_user_id` AS receiver_user_id, `
t1`.`sender_user_id` AS sender_user_id,
`t1`.`created_at` AS created_at
FROM `messages` `t1`
WHERE `t1`.`sender_user_id` = 50
UNION
SELECT `t2`.`sender_user_id` AS other_user_id,
`t2`.`receiver_user_id` AS receiver_user_id,
`t2`.`sender_user_id` AS sender_user_id,
`t2`.`created_at` AS created_at
FROM `messages` `t2`
WHERE `t2`.`receiver_user_id` = 50
Any idea why there's a MySQL UNION error. Is it an arel bug?
Secondly, any help with completing the query would be much appreciated.
Update:
Using Arel::Nodes::Union.new works
I think this is more probably a mysql fault, this is a mySQL error text. Something similar is discussed in here, but not exactly this issue.
Try to migrate to another sql server, and check again, or if union all works then use this:
conv = convs1.union(convs2, :all)
Based on documentation.
The problem is actually the parentheses in the sql. It works if I run:
Message.find_by_sql conv.to_sql.delete('()')
which removes the leading "(" and trailing ")"
Weird.. I don't know how I would chain this to complete the query. (Arel::Nodes::Union doesn't have a group method). This is Rails 3.1.4
I had a similar problem and solved it as follows:
def last_messages
Message.find_by_sql("
SELECT messages.*,
(IF(recipient_id = #{id}, 0,1)) as outlast,
users.avatar_name,
users.name
FROM messages
INNER JOIN users
ON users.id=(IF(recipient_id = #{id}, sender_id,recipient_id))
WHERE messages.id IN
( SELECT max(id)
FROM messages
WHERE recipient_id = #{id} OR sender_id = #{id}
GROUP BY (IF(recipient_id = #{id}, sender_id, recipient_id))
)
ORDER BY messages.id DESC")
end
This is the code I used instead in the end
all_msgs = Message.where("messages.sender_user_id = ? OR messages.receiver_user_id = ?",
user.id, user.id)
msg_ids = all_msgs.select("sender_user_id, receiver_user_id, max(id) as max_id")
.group(:sender_user_id, :receiver_user_id).map { |m| m.max_id }
all_msgs = all_msgs.where(:id => msg_ids)