SQL Code:
SELECT id, album_date AS timestamp, CONCAT((SELECT detail_value
FROM people_db.user_details_tbl WHERE detail_field = 'first_name' AND user_id = pictures_db.albums.owner), ' uploaded pictures!') AS title_html
FROM pictures_db.albums
WHERE id IN
(SELECT DISTINCT(album_id)
FROM pictures_db.album_pics
WHERE pic_id IN
(SELECT DISTINCT(picture_id)
FROM pictures_db.picture_access_tbl
WHERE grantee_group_id IN
(SELECT group_id
FROM people_db.group_membership_tbl
WHERE member_id = '2'
)
)
);
PHP Code:
$albums_sql = mysql_query("SELECT id, album_date AS timestamp, CONCAT((SELECT detail_value
FROM people_db.user_details_tbl
WHERE detail_field = 'first_name' AND user_id = pictures_db.albums.owner), ' uploaded pictures!') AS title_html
FROM pictures_db.albums
WHERE id IN (
SELECT DISTINCT(album_id)
FROM pictures_db.album_pics
WHERE pic_id IN (
SELECT DISTINCT(picture_id)
FROM pictures_db.picture_access_tbl
WHERE grantee_group_id IN (
SELECT group_id
FROM people_db.group_membership_tbl
WHERE member_id = '2'
)
)
)") or die(mysql_error());
When the PHP is run, the error is: Table 'pictures_db.albums' doesn't exist
I tried executing as the same user, regranted all permissions, and even flushed privileges. Works in shell, not in PHP.
Any ideas?
The error message is quite clear: MySQL sees the database pictures_db but not the table albums.
That could be due to permissions, but you seem to have checked that thoroughly.
Another possible reason is that the connection string you're using in PHP points to a different database instance than the one you're using at the command line. Perhaps the connection string still points to a different environment, such as DEV but you're in QA or points to an old test version of the database?
Do you call mysql_select_db() before running the query?
mysql_select_db('pictures_db');
Related
(django 3.2.12, python 3.9.3, MySQL 8.0.28)
Imagine models like the following:
class User(models.Model):
email = models.EmailField(...)
created_datetime = models.DatetimeField(...)
class UserLog(models.Model):
created_datetime = models.DatetimeField(...)
user = models.ForeignKey('user.User' ...)
login = models.BooleanField('Log in' ..)
And the following query, destined to annotate each user in the queryset with the frequency of their logs(when log.login=True):
users = User.objects.filter(
Q(...)
).annotate(
login_count=Count('userlog', filter=Q(userlog__login=True)),
login_duration_over=Now() - F('created_datetime'),
login_frequency=ExpressionWrapper(
F('login_duration_over') / F('login_count'),
output_field=models.DurationField()
),
)
This results in a SQL error:
(1064, "You have an error in your SQL syntax;)
The generated SQL (fragment for login_frequency) looks like this:
(
INTERVAL TIMESTAMPDIFF(
MICROSECOND,
`user_user`.`created_datetime`,
CURRENT_TIMESTAMP
) MICROSECOND / (
COUNT(
CASE WHEN `user_userlog`.`login` THEN `user_userlog`.`id` ELSE NULL END
)
)
) AS `login_frequency`,
and MySQL does not seem to like it. A similar code works on SQLlite and, I am told on PG.
What is wrong with the ExpressionWrapper on MySQL, any idea?
Found a workaround:
users = User.objects.filter(
Q(...)
).annotate(
login_count=Count('userlog', filter=Q(userlog__login=True)),
login_duration_over=Now() - F('created_datetime'),
login_frequency=Cast(
ExpressionWrapper(
Cast(F('login_duration_over'), output_field=models.BigIntegerField()) / F('login_count'),
output_field=models.BigIntegerField()
),
output_field=models.DurationField()
)
)
this forces the DIVIDE operation to be performed db-side on bigints and once that is done, cast it back to a timedelta.
MySQL stopped screaming and the results are correct.
Even though that work, this feels ugly. Could there not be a better way?
I'm new to MySQL and I'm trying to make the following pseudocode work:
SELECT IF(
EXISTS(SELECT * FROM users WHERE `email`="admin" AND `token`="blablabla"),
(UPDATE * FROM sometable WHERE `var`="notimportant"),
"NOT_AUTHORIZED");
What I'm trying to achieve is running code based on the presence of a row, and if it doesn't exists return a message, or something usable. If it does exists, run another SQL command instead, and return those results.
Is this possible?
Your intent is a bit hard to follow from the invalid syntax. But the gist of your question is that you can use a where clause:
UPDATE sometable
SET . . .
WHERE var = 'notimportant' AND
EXISTS (SELECT 1 FROM users WHERE email = 'admin' AND token = 'blablabla');
You can also represent this as a JOIN. Assuming the subquery returns at most one row:
UPDATE sometable t CROSS JOIN
(SELECT 1
FROM users
WHERE email = 'admin' AND token = 'blablabla'
LIMIT 1
) x
SET . . .
WHERE var = 'notimportant' ;
My question has 2 parts, and i am unsure if it is my query which is causing the error or data adapter.
Part 1. I have a mySQL query which works fine on SQLyog, the query involves selection from tables existing in different databases. And both databases has been set to have the same accecss rights for the user account used at the connection string.
Below will be my query.
SELECT `portaldb`.`users`.`full_name` AS 'Name of User'
,`Systemrevamp`.`System_countries`.`CountryName` AS 'Quoted For'
,`Systemrevamp`.`uniquequote`.`UniqueQuote` AS 'System Quote ID'
, IF (
LEFT(`Systemrevamp`.`uniquequote`.`username`, 1) = ' '
,'Web Access'
,'Bulk Upload'
) AS 'Type'
,DATE_FORMAT(`Systemrevamp`.`uniquequote`.`insertedon`, '%d-%b-%Y') AS 'Quoted On'
FROM `portaldb`.`users`
INNER JOIN `Systemrevamp`.`uniquequote` ON TRIM(`Systemrevamp`.`uniquequote`.`UserName`) = `portaldb`.`users`.`usrname`
INNER JOIN `Systemrevamp`.`System_countries` ON `Systemrevamp`.`System_countries`.`Code` = `Systemrevamp`.`uniquequote`.`CountryCode`
INNER JOIN `portaldb`.`permission_details` ON `portaldb`.`permission_details`.`user_ID` = `portaldb`.`users`.`user_ID`
WHERE `portaldb`.`permission_details`.`group_ID` = '5'
AND `Systemrevamp`.`uniquequote`.`insertedon` >= (NOW() - INTERVAL 3 MONTH)
ORDER BY `portaldb`.`users`.`full_name` ASC,`Systemrevamp`.`uniquequote`.`insertedon` ASC
Visual studio keeps telling me there is syntax error and to check the version of SQL, but I am able to retrieve at the database.
Part 2. Below is a snippet of my code. My question for this part is, if the above query is used, what source table should I put for the data adapter to fill at 'XXX'?
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
allUserDataset = New DataSet()
myDataAdapter.Fill(allUserDataset, "XXX")
gvAllQuotes.DataSource = allUserDataset
gvAllQuotes.DataBind()
Please let me know if more information is needed. Thank you.
I have the following virtual field on my Page model
function __construct($id = false, $table = null, $ds = null) {
$this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0';
parent::__construct($id, $table, $ds);
}
This works as expected and displays the number of users who have added the page to their favorites. The issue is that, during development, some rows have duplicate user_id to page_id pairs so it returns the incorrect number or unique users. I tried adding a group by clause like so
$this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0 GROUP BY Favorite.user_id';
But it does not work. I tried debugging the issue but I receive the error message "allowed memory size exhausted". I also tried using SELECT COUNT('Favorite.user_id') and SELECT DISTINCT('Favorite.user_id') neither of which worked either. I believe DISTINCT is further away from the answer as that would return an array (I believe?)
Is this a known CakePHP issue? Am I implementing the group by wrong? Is there another solution to do this other than afterfind?
try this
SELECT COUNT(DISTINCT Favorite.user_id)
like that :
$this->virtualFields['fans'] = 'SELECT COUNT(DISTINCT id) FROM favorites WHERE status = 0';
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)