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' ;
I have an entity called tracking. It relates to a User and a Course.
I also have an entity called credential which officially links User and Course
User <- Tracking -> Course || User <- Credential -> Course
Tracking is a joining entity of sorts, but it's not the primary join between the two. I have a query where I already have the user and the course joined, and I want to left-join the tracking if it exists. I've tried to simplify my example.
$q->select(
'user.id',
'user.firstname',
'user.lastname',
'count(t) as courses',
'count(t.completed) as completed'
);
$q->from(Credential::class, 'c');
$q->from(Course::class, 'course');
$q->from(User::class, 'user');
$q->leftJoin(Tracking::class, 't', 'WITH', 't.user = user and t.course = course');
$q->where('c.user = user and c.object = course');
$q->groupBy('user');
What I'm trying to achieve here, is a list of users who are enrolled in courses, the number of courses, and where possible the number of completed courses.
Unfortunately, doctrine can only seem to join to either the user table or the course table, but not to both. This might even be a mysql limitation. I've debugged this over and over - and I've run into the problem several times with different examples - and I just can't seem to find a solution other than using ->from(Tracking) which would eliminate students who haven't started any courses, and stats from courses they haven't started. I've googled over and over again, but It's so hard to search for this problem and not get 'How to join two tables with Doctrine'.
I get the error Column not found: 1054 Unknown column 'c1_.id' in 'on clause' which I assume means it can join on t.user = user but not t.course = course
Here is the actual code and error
$q = $this->em->createQueryBuilder();
$q->select(
'user.id',
'user.firstname',
'user.lastname',
'count(sc.id) as courses',
'count(ct.commenced) as commenced',
'count(ct.completed) as completed',
'avg(ct.scorePercent) as avgscore',
'avg(ct.totalTime) as avgtime'
);
$q->from(Security\Credential::class, 'c');
$q->from(Security\SecurableCourse::class, 'sc');
$q->from(Security\AccreditableInheritance::class, 'ai');
$q->from(Security\AccreditableUser::class, 'au');
$q->from(User::class, 'user');
$q->join(Tracking\CourseTracking::class, 'ct', 'WITH', 'ct.objectIdentity = sc and ct.user = user');
$q->where('sc = c.securable and ai.parent = c.accreditable and au = ai.child and user = au.user');
$q->andWhere('c.action = :action and sc.course in (:courses)');
$q->setParameter('action', 'study')->setParameter('courses', $courses);
$q->groupBy('user.id');
$users = $q->getQuery()->getScalarResult();
Doctrine\DBAL\Exception\InvalidFieldNameException(code: 0): An exception occurred while executing 'SELECT u0_.id AS id_0, u0_.firstname AS firstname_1, u0_.lastname AS lastname_2, count(s1_.id) AS sclr_3, count(t2_.commenced) AS sclr_4, count(t2_.completed) AS sclr_5, avg(t2_.scorePercent) AS sclr_6, avg(t2_.totalTime) AS sclr_7 FROM Credential c3_ INNER JOIN Tracking t2_ ON (t2_.objectIdentity_id = s1_.id AND t2_.user_id = u0_.id) AND t2_.dtype IN ('coursetracking') AND ((t2_.deleted IS NULL OR t2_.deleted > '2016-04-26 08:33:31')), SecurableIdentity s1_, AccreditableInheritance a4_, AccreditableIdentity a5_, User u0_ WHERE (((s1_.id = c3_.securable_id AND a4_.parent_id = c3_.accreditable_id AND a5_.id = a4_.child_id AND u0_.id = a5_.user_id) AND (c3_.action = ? AND s1_.course_id IN (?, ?, ?))) AND ((u0_.deleted IS NULL OR u0_.deleted > '2016-04-26 08:33:31'))) AND (s1_.dtype IN ('securablecourse') AND a5_.dtype IN ('accreditableuser')) GROUP BY u0_.id' with params [\"study\", \"46\", \"45\", \"160\"]:\n\nSQLSTATE[42S22]: Column not found: 1054 Unknown column 's1_.id' in 'on clause'
This is just a hint how to achieve it. I cannot give you the correct answer as you don't give enough details. But this will help you to achieve what you need.
$q->select(u, t, co, ce);
$q->from('User', 'u');
$q->leftJoin('u.tracking', 't');
$q->leftJoin('t.course', 'co');
$q->leftJoin('u.credential', 'ce');
I have a number of tables in my wordpress database(gooda814_bilby01). I want a function to compare the tables in the database with the values in a column in a table in the database so that the function will then create any table not on the list. I have a php solution that is inelegant:
$fdc_tables = $wpdb->get_results('SELECT distinct `fdc_form` FROM `fdc_tables`', ARRAY_A);
$wp_tables = $wpdb->get_results('show tables from gooda814_bilby01', ARRAY_A);
foreach( $fdc_tables as $fkey => $fvalue ) { $fdc[$fkey] = $fvalue['fdc_form']; }
foreach( $wp_tables as $wkey => $wvalue ) { $wpt[$wkey] = $wvalue['Tables_in_gooda814_bilby01']; }
$required tables = (array_values((array_diff($fdc, $wpt))));
but I thought there might be a neat mysql join like:
select distinct fdc_forms from
join show tables on Tables_in_gooda814_bilby01 = fdc_tables.fdc_forms
However, this of course returns an error #1064
Use a Sub-Query instead of a JOIN.
Try this SQL
SELECT fdc_form
FROM fdc_tables
WHERE fdc_form NOT IN (
SELECT T.TABLE_NAME
FROM information_schema.TABLES T
WHERE T.TABLE_SCHEMA='gooda814_bilby01'
);
I want to recuperate all rows from user table.
String queryS = "select u from user u";
System.out.println("entityManager: "+(entityManager == null));
Query query = entityManager.createQuery(queryS);
//staff
The line that throws the exception is Query query = entityManager.createQuery(queryS);
I don't know why even persistance file is ok and the table exists
The stack is:
10:36:06.693 [AWT-EventQueue-0] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
10:36:06.693 [AWT-EventQueue-0] DEBUG o.h.hql.antlr.HqlSqlBaseWalker - select << begin [level=1, statement=select]
You have to put the name of the table in the query as in the persistence file not in database.
If this:
String queryS = "select u from user u"
Is referred on table name you can't use createQuery method but createNativeQuery
If you want to use createQuery you must use in your query the entity/class mapped youe user table
Summarizing:
Case 1 (use createNativeQuery)
String queryS = "select u from user u";
Query query = entityManager.createNativeQuery(queryS);
Case 2 (use createQuery)
String queryS = "select u from " + User.class.getName() + " u";
Query query = entityManager.createNativeQuery(queryS);
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');