So I have been lookin for mistake for a while, but still can't find it.
Here is the code -
$this->db->select('*');
$this->db->from('friendRequests');
$this->db->where(array('friendRequests.status' => 1, 'users.status' => 1));
$this->db->or_where(array('friendRequests.senderId' => $this->session->userdata('userId'), 'friendRequests.receiverId' => $this->session->userdata('userId')));
$this->db->join('users', 'users.id = '.$this->session->userdata('userId'));
$query = $this->db->get();
It provides me this error -
Unknown column '1' in 'on clause'
SELECT *
FROM (`friendRequests`)
JOIN `users` ON `users`.`id` = `1`
WHERE `friendRequests`.`status` = 1
AND `users`.`status` = 1
OR `friendRequests`.`senderId` = '1'
OR `friendRequests`.`receiverId` = '1'
If an entry is surrounded in backticks it counts as a column even if it would not be one without the backtics. It thinks that 1 is a column on the JOIN line because of this.
Apparently this is a product of the join method in CI. You can fix it very easily by moving that condition to the WHERE clause. There's no need for it to be in the JOIN clause.
JOIN does not work that way; the syntax is:
JOIN 'tablename' ON 'tablename.field' = 'othertable.field'
If I had to assume you were trying to get a user's friend requests:
JOIN 'users' ON 'users'.'id' = 'friendRequests'.'receiverId'
Related
I have given my Codeigniter code below, here i need to update a record using join conditions. I used the below code, But shows error
$condition="a.assignto='0' and a.recstatus='1' and b.location='$location' and '$category' IN(SELECT categoryid FROM `tq_productcategory` where productid=c.productid and recstatus='1')";
$this->db->set($data);
$this->db->where($condition);
$this->db->limit($limit);
$this->db->join('tq_customer b','a.customerid=b.customerid');
$this->db->join('tq_product c','a.productid=c.productid');
$this->db->order_by("a.created_on", "asc");
$this->db->update('tq_customerservicesupport a');
Below is my error Msg
Unknown column 'b.location' in 'where clause'
UPDATE `tq_customerservicesupport` `a` SET `assignto` = '10' WHERE `a`.`assignto` = '0' and `a`.`recstatus` = '1' and `b`.`location` = '3227' and '1' IN(SELECT categoryid FROM `tq_productcategory` where productid = `c`.`productid` and `recstatus` = '1') ORDER BY `a`.`created_on` ASC LIMIT 1
Filename: D:/wamp/www/tooquik/system/database/DB_driver.php
Try this:
$sql = "UPDATE tq_customerservicesupport AS a JOIN tq_customer AS b ON a.customerid = b.customerid JOIN tq_product AS c ON a.productid = c.productid SET $data WHERE $condition ORDER BY a.created_on ASC LIMIT $limit";
$this->db->query($sql);
Make sure that the query is correct cause i just wrote it based on your data and better to check it in phpmyadmin to make sure it works fine with no errors.
I have the following query using findbysql:
$query = Users::findBySql('select a.user_id, a.last_name,a.first_name, a.emp_id, ar.role_id from auth_users a, auth_user_roles AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
where AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
AND D.DEPT_GROUP_ID = :dept_group_id AND (ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)
UNION
SELECT DISTINCT a.user_id, a.last_name, a.first_name, a.emp_id, NULL AS role_id FROM auth_users a, AUTH_USER_ROLES AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
WHERE AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
AND D.DEPT_GROUP_ID = :dept_group_id AND
AR.ACCESS_END_DATE < SYSDATE AND AR.USER_ID NOT IN (select USER_ID from auth_user_roles where ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)', [':dept_group_id' => $dept_group_id ]);
This query does exactly what I want it to, but the problem is when I try to put it into a gridview it does not sort. According to Sort and search column when I'm querying with findbysql in yii2 it seems like I need to use query builder instead.
So I was trying to do that with the first part of my query (before the union), and it looks like so:
$query1 = (new \yii\db\Query())
->select(['user_id', 'last_name', 'first_name', 'emp_id'])
->from('AUTH_USERS');
$query2 = (new \yii\db\Query())
->select('USER_ID')
->from('AUTH_USER_ROLES')
->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
$query = $query1->innerJoin('AUTH_USER_DEPTS', 'AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id')->innerJoin('DEPARTMENTS', 'AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id');
$query->innerJoin('AUTH_USER_ROLES', 'AUTH_USER_ROLES.USER_ID = auth_users.USER_ID')->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
However, my query comes out like this in yii and apparently oracle is not accepting the double quotes around the column names:
SELECT "user_id", "last_name", "first_name", "emp_id" FROM "AUTH_USERS"
INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id
INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id
INNER JOIN "AUTH_USER_ROLES" ON AUTH_USER_ROLES.USER_ID = auth_users.USER_ID
WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL
I know the query might be incorrect here already but I cant even get the double quotes to go away. Tried defining the select statements multiple ways suggested by the yii docs already with no success:
select(['user_id', 'last_name', 'first_name', 'emp_id'])
select('user_id', 'last_name', 'first_name', 'emp_id')
select("user_id, last_name,first_name,emp_id")
I have also tried joining the queries like this from the docs: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
$query = $query1->innerJoin(['u' => $query2], 'u.user_id = user_id');
but it also complains that it doesnèt recognize u and the query instead comes out like so in yii:
SELECT COUNT(*) FROM "AUTH_USERS" INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id INNER JOIN (SELECT "USER_ID" FROM "AUTH_USER_ROLES" WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL) "u" ON u.user_id = auth_users.user_id
At this point im just looking for the easiest way to build this query (whether it be using querybuilder or some other way) so that I can pass the query to my gridview and sort it.
I would recommend you first create all the data models you need from the tables you need for the query, using Gii it should be easy and it even creates the relationships you will need.
After that, you can do something like the following:
$query = Users::find()
->joinWith('theRelation1Name')
->joinWith('theRelation2Name')
->joinWith('theRelation3Name')
...
This way you don't need to give tables aliases or add the conditions needed for the relations to work.
At the moment i have this query:
$qry = "SELECT platforms.PID
FROM user_profile
LEFT JOIN platforms
ON platforms.relaccount = user_profile.subkey
WHERE user_profile.UID = `".$data['id']."`";
$games = $this->db->select('main.APPID, games_other.name, games_other.logo')
->select('platforms.PID, platforms.name AS pname, platforms.logo AS plogo')
->select('('.$qry.') AS filt', null, FALSE)
->from('games_link AS main')
->join('games_platforms', 'games_platforms.APPID = main.APPID', 'left')
->join('platforms', 'platforms.PID = games_platforms.PID', 'left')
->join('games_other', 'games_other.APPID = main.GB_ID', 'left')
->like('games_other.name', $name)
->where('platforms.PID', 'filt')
->limit(15)
->get();
Where im trying to get games based on an input string but filtered by what platforms a user has, but it returns this error:
Unknown column 'Cf9nHvOlaaLzFRegX2Il' in 'where clause'
SELECT `main`.`APPID`, `games_other`.`name`, `games_other`.`logo`, `platforms`.`PID`, `platforms`.`name` AS pname, `platforms`.`logo` AS plogo, (SELECT platforms.PID FROM user_profile LEFT JOIN platforms ON platforms.reaccount = user_profile.subkey WHERE user_profile.UID = `Cf9nHvOlaaLzFRegX2Il`) AS filt FROM (`games_link` AS main) LEFT JOIN `games_platforms` ON `games_platforms`.`APPID` = `main`.`APPID` LEFT JOIN `platforms` ON `platforms`.`PID` = `games_platforms`.`PID` LEFT JOIN `games_other` ON `games_other`.`APPID` = `main`.`GB_ID` WHERE `platforms`.`PID` = 'filt' AND `games_other`.`name` LIKE '%a%' LIMIT 15
Filename: response/update.php
I have tried changing a few things around but nothing fixes this.
Also since I Havant been able to get there yet, would this work as a filter. The sub query will return multiple.
You have a column value with backticks and its not valid it should be single quote or no quote if its INTEGER
$qry = "SELECT platforms.PID
FROM user_profile
LEFT JOIN platforms
ON platforms.reaccount = user_profile.subkey
WHERE user_profile.UID = '".$data['id']."'";
Your problem is here:
WHERE user_profile.UID = `Cf9nHvOlaaLzFRegX2Il`
Backticks, `, escape database objects (view names, table names, column names ... etc).
String values should be escaped with single quotes, '.
I would be wary of concatenating in values, you should probably bind them in if possible.
Here is the code:
$f = DB::table("topics")
->join("recommends", "topics.id", "=", "recommends.courseid")
->where("recommends.re_type", "=", $re_type)
->where("recommends.re_location", "=", $re_location)
->orderBy("recommends.weigh", "desc");
$s = DB::table("topics")
->orderBy("topics.create_time", "desc");
$f->union($s)->get();
I got a wrong SQL around key word union:
select * from `topics` inner join `recommends`
on `topics`.`id` = `recommends`.`courseid`
where `recommends`.`re_type` = ?
and `recommends`.`re_location` = ?
order by `recommends`.`weigh` desc
union //here!!!!!
select * from `topics` order by `topics`.`create_time` desc
The error info:
SQLSTATE[HY000]: General error: 1221
Incorrect usage of UNION and ORDER BY (SQL: ...)
(Bindings: array ( 0 => 3, 1 => 7, ))
What is the problem?
MySQL UNIONs expect the same columns in all statements. Because you're joining another table in $f, the columns between the two statements don't match.
See MySql SELECT union for different columns?
In this case, it might be less of a headache to use the PDO object directly.
$pdo = DB::connection()->getPdo();
Found another problem with your query. You should relocate your first order by clause:
->orderBy("recommends.weigh", "desc");
It is producing the order by you before union and MySQL will not accept that.
I have this code running
$sq = $this->_codes->getAdapter()->select()
->from (array('cs' => 'code_statuses'), array('total' => 'count(*)'))
->join (
array ('c' => 'codes'), 'c.code_id = cs.code_id',
array ('human_state' => new Zend_Db_Expr("CASE c.state_id WHEN 3 THEN 'active' WHEN 5 THEN 'suspended' ELSE 'inactive' END"), 'c.*')
)
->group('cs.code_id');
$sqtemp = $this->_codes->getAdapter()->select()
->from (array('cs' => 'code_statuses'), array('total' => 'count(*)'))
->join (
array ('c' => 'codes'), 'c.code_id = cs.code_id',
array ('human_state' => new Zend_Db_Expr("CASE c.state_id WHEN 3 THEN 'active' WHEN 5 THEN 'suspended' ELSE 'inactive' END"), 'c.*')
)
->group('cs.code_id');
if (!empty($options['state_id'])):
if (is_array($options['state_id'])):
$states = 'cs.state_id=' . implode(' OR cs.state_id=', $options['state_id']);
$sq->where($states)
->having(total<=4);
$sqtemp->where ('cs.state_id=5')
->having(total<4);
else:
$sq->where ('cs.state_id=?', $options['state_id']);
endif;
The issue occurs when i try to use union
$sqfinal=$this->_codes->getAdapter()->select()
->union(array($sq,$sqtemp))
->order('cs.code_id');
but individually $sq and $sqtemp work fine
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cs.code_id' in 'order clause'
Not sure where I am going wrong
Any help will be appreciated
*edit
SELECT count(*) AS `total`,
CASE c.state_id
WHEN 3 THEN 'active'
WHEN 5 THEN 'suspended'
ELSE 'inactive'
END AS `human_state`, `c`.*
FROM `code_statuses` AS `cs`
INNER JOIN `codes` AS `c`
ON c.code_id = cs.code_id
WHERE (cs.state_id=1 OR cs.state_id=2 OR cs.state_id=4)
GROUP BY `cs`.`code_id` HAVING (total<=4)
UNION
SELECT count(*) AS `total`,
CASE c.state_id
WHEN 3 THEN 'active'
WHEN 5 THEN 'suspended'
ELSE 'inactive'
END AS `human_state`, `c`.*
FROM `code_statuses` AS `cs`
INNER JOIN `codes` AS `c`
ON c.code_id = cs.code_id
WHERE (cs.state_id=5)
GROUP BY `cs`.`code_id`
HAVING (total<4)
The part before the union is $sq, the part afterwards is $sqtemp, the combination of the two gives the print out above
Both of them with union in is the whole thing
After a second look at your code, I suspect the oder() call on the union. You're ordering by cs.code_id, whic is not mentioned in any of the select statements, nor is the c.code_id for that matter.
Try adding either c.code_id or cs.code_id to the SELECT't that make up the UNION, possibly consider using an alias, which you can then use in your order clause.
$sq = $this->_codes->getAdapter()->select()
->from(array('cs' => 'code_statuses'),
array(
'total' => 'count(*)'
'cscodeids' => 'code_ids',
));
//...
$union = $this->_codes->getAdapter()
->select()
->union(array($sq,$sqtemp))
->order('cscodeids');
This, I believe, should work. I've taken inspiration from various places. Here are some of the links that lead up to my answer (can't find all of them ATM):
MySQL union and order by help
Every derived table must have its own alias - error from combination descending MySQL
Using union and order by clause in mysql
How to use union in zend db
Zend_Db union issue: old bug report... contains some details