Codeigniter join query multiple conditions don't work - php

I want to select data from my database table with join query, but my it doesn't work.
My query:
$this->db->select();
$this->db->from('we');
$this->db->join('schedule', 'schedule.itemid = we.cid');
$this->db->join('schedule', 'schedule.itemtype = 'testitem'');
$this->db->where('we.isActive','Y');
This line makes problem with schedule.itemtype = 'testitem':
$this->db->join('schedule', 'schedule.itemtype = 'testitem'');
How can I solve this?

You don't need to join same table twice.
But just to extend ON clause:
$this->db->select();
$this->db->from('we');
$this->db->join('schedule', 'schedule.itemid = we.cid AND schedule.itemtype = \'testitem\'');
$this->db->where('we.isActive','Y');

try
$this->db->select();
$this->db->from("we");
$this->db->join("schedule", "schedule.itemid = we.cid");
$this->db->where("schedule.itemtype","testitem");
$this->db->where("we.isActive","Y");

I believe there are two problems here. The first problem is that you are using one too many quotes in the second join line in your query:
You have: $this->db->join('schedule', 'schedule.itemtype='testitem''); < extra quote
It should be: $this->db->join('schedule', 'schedule.itemtype=testitem');
Second problem: your join doesnt make sense.
Your statement:
$this->db->select();
$this->db->from('we');
$this->db->join('schedule', 'schedule.itemid = we.cid');
$this->db->join('schedule', 'schedule.itemtype = testitem');
$this->db->where('we.isActive','Y');
Translates to:
SELECT * FROM we
JOIN schedule ON schedule.itemid = we.cid
JOIN schedule ON schedule.itemtype = testitem
WHERE we.isActive = Y
As you can see you are joining the same table twice on different lines, not only that but what table does "testitem" belong to? We are left to assume that you perhaps want the join where itemtype = testitem which will mean this:
SELECT * FROM we
JOIN schedule ON schedule.itemid = we.cid
WHERE schedule.itemtype = testitem
AND we.isActive = Y
Therefore your final Codeigniter query should be:
$this->db->select('*');
$this->db->from('we');
$this->db->join('schedule', 'schedule.itemid = we.cid');
$this->db->where('schedule.itemtype', 'testitem');
$this->db->where('we.isActive','Y');

This will work:
$this->db->join('schedule', 'schedule.itemid = we.cid');
$this->db->where('we.isActive','Y');
$this->db->where('schedule.itemtype', 'testitem');
$this->db->get('we');

$this->db->query('select we_tbl.c_name from we we_tbl,schedule sch_tbl where sch_tbl.itemid = we_tbl.cid AND we_tbl.idActive = '.$activeData);
Try this query according to your problem this could get the data you need.
I've tested on different database but i tried to perform what you're trying to get. https://www.w3schools.com/sql/trysql.asp?filename=trysql_op_in
select
pro_tbl.ProductName,
cat_tbl.CategoryName ,
sup_tbl.SupplierName
from
Products pro_tbl,
Suppliers sup_tbl,
Categories cat_tbl
where
pro_tbl.SupplierID = sup_tbl.SupplierID AND
pro_tbl.CategoryID = cat_tbl.CategoryID;

Two possible problems, depending on what your desired outcome is:
If you need to make two joins and are getting an error with the second join clause, try using double quotes to enclose the constant value on the condition or you'll get a parse error:
$this->db->join('schedule', 'schedule.itemtype = "testitem"');
If you need to join only once with multiple conditions, use parentheses:
$this->db->select('*');
$this->db->from('we');
$this->db->join('schedule', '(schedule.itemid = we.cid AND schedule.itemtype="testitem")');
$this->db->where('we.isActive','Y');
You query is equivalent to writing:
select * from we
inner join schedule on schedule.itemid = we.cid
inner join schedule on schedule.itemtype = "testitem"
where we.isActive = 'Y'
but what you seem to need is
select * from we
inner join schedule on (schedule.itemid = we.cid AND schedule.itemtype = "testitem")
where we.isActive = 'Y'
On your original query, you are doing two joins. In the latter, you'll do only one with multiple conditions.

Related

Yii2 translating findBySql query to QueryBuilder query

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.

How to query 2 tables

I need to sum the transactions in tblgl (tblgl.SUM(InMonthActual)) for a selection of cost centres (tblgl.CostCentreCode) where the following conditions are met:
tblgl.PeriodNumber = 2
tblgl.CostCentreCode = tblcostcentrehierarchy.CostCentreCode
WHERE tblcostcentrehierarchy.Level7 = "RWK312 CORPORATE"
tblgl.CostCentreCode = tblcostcentreallocations.CostCentreCode
WHERE tblcostcentreallocations.Username = "jonest"
At the moment I'm running 3 separate queries to create an array which is used in the next query.
Is there a way to do it in one (maybe using JOIN)?
I hope this query will fetch your desire data. Check and let me know if it works for you.
SELECT SUM(tb1.`InMonthActual`)
FROM `tblgl` as tb1
JOIN `tblcostcentrehierarchy` as tb2 ON tb1.`CostCetntreCode` = tb2.`CostCentreCode`
JOIN `tblcostcentreallocations` as tb3 ON tb1.`CostCetntreCode` = tb3.`CostCentreCode`
WHERE tb1.`PeriodNumber` = '2' AND tb2.`Level17` = "RWK312 CORPORATE" AND tb3.`Username` = "jonest"
Give it a try
SELECT SUM(tblgl.InMonthActual) FROM tblgl
INNER JOIN tblcostcentrehierarchy ON (tblgl.CostCentreCode = tblcostcentrehierarchy.CostCentreCode AND tblgl.PeriodNumber = 2)
INNER JOIN tblcostcentreallocations ON (tblgl.CostCentreCode = tblcostcentreallocations.CostCentreCode)
WHERE tblcostcentreallocations.Username = "jonest" AND tblcostcentrehierarchy.Level7 = "RWK312 CORPORATE"
GROUP BY tblgl.InMonthActual
Hope it works fine

Zend DB select only 1 table with multiple joins

I'm using Zend DB to generate a query using the following code:
$table->select()
->setIntegrityCheck(false) //required for multi-table join
->from('modules')
->joinInner(
'basket_modules',
'modules.id = basket_modules.id')
->joinInner(
'baskets',
'baskets.id = basket_modules.basket_id')
->where('baskets.id = ?', $this->id);
This generates the SQL:
SELECT modules.*, basket_modules.*, baskets.*
FROM modules
INNER JOIN basket_modules ON modules.id = basket_modules.id
INNER JOIN baskets ON baskets.id = basket_modules.basket_id
WHERE (baskets.id = '3')
My problem here is with the SELECT part, it's selecting all 3 tables instead of just modules, which is the one I want. So the query I would want to generate is:
SELECT `modules`.*
FROM `modules`
#etc...
How can I do this? If I edit the query manually and run it, it returns what I want so there shouldn't be a problem with the syntax.
Please look at the example in the manual Zend_Db_Select. Scroll to the Example #13.
To select no columns from a table, use an empty array for the list of
columns. This usage works in the from() method too, but typically you
want some columns from the primary table in your queries, whereas you
might want no columns from a joined table.
$select = $db->select()
->from(array('p' => 'products'),
array('product_id', 'product_name'))
->join(array('l' => 'line_items'),
'p.product_id = l.product_id',
array() ); // empty list of columns
you can specify column name for other table and main table like below
$table->select()
->setIntegrityCheck(false) //required for multi-table join
->from('modules',array('modules.*'))
->joinInner(
'basket_modules',
'modules.id = basket_modules.id',array('basket_modules.id'))
->joinInner(
'baskets',
'baskets.id = basket_modules.basket_id',array('baskets.id'))
->where('baskets.id = ?', $this->id);
so sql will be like
SELECT modules.*, basket_modules.id, baskets.id
FROM modules
INNER JOIN basket_modules ON modules.id = basket_modules.id
INNER JOIN baskets ON baskets.id = basket_modules.basket_id
WHERE (baskets.id = '3')
$table->select()
->setIntegrityCheck(false) //required for multi-table join
->from('modules')
->joinInner(
'basket_modules',
'modules.id = basket_modules.id',array(''))
->joinInner(
'baskets',
'baskets.id = basket_modules.basket_id',array(''))
->where('baskets.id = ?', $this->id);
Give a empty array as the third parameter of join otherwise it will select all the field from the table joined.If you want some fields then specify field names in the array while joining.

mySQL query with JOIN on latest record not all records

The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.
$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0"
The problem is that some electors will have more than one pledge in the voting_intentions table.
I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.
What is the simplest way of implementing that.
The rest of the code:
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) {
echo $row['ID'].','; }
}
You could use a sub-select with the MAX() function. Add the following into your WHERE clause.
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
Here is a SQLFiddle of the results.
So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here.
Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):
SELECT voting_intention.*
FROM voting_intention
INNER JOIN
(
SELECT elector, MAX(date) AS MaxDate
FROM voting_intention
GROUP BY elector
) groupedintention ON voting_intention.elector = groupedintention.elector
AND voting_intention.date = groupedintention .MaxDate
Question url: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Duplicate values returning from mySQL JOIN Statement. Help?

I am having a hard time creating a mySQL join statement.
The issue is that it seems to return the correct results, but it returns duplicates.
$result= mysql_query("SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
WHERE PhotoUserTags.User_ID IN ($friendlist) && PhotoUserTags.Photo_ID = Photos.Photo_ID && Photos.Event_ID = $eid");
I am new to these statements, any help or guidance is greatly appreciated.
Here's your query:
SELECT
Photos.Filename, Photos.Filetype
FROM Photos
INNER JOIN PhotoUserTags ON (PhotoUserTags.Photo_ID = Photos.Photo_ID)
WHERE
Photos.Event_ID = $eid
AND PhotoUserTags.User_ID IN ($friendlist) /* assuming they are IDs separated by a comma) */
GROUP BY Photos.Photo_ID;
I would also explain this query just in case you use the right indexes to maximize the performance of your query
For one, the logical and in mysql is not && but AND, like this:
SELECT * from table WHERE field1 = 'value1' AND field2 = 'value2';
You should also use the newer join syntax like this:
SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
INNER JOIN PhotoUserTags ON PhotoUserTags.Photo_ID = Photos.Photo_ID
WHERE PhotoUserTags.User_ID IN ($friendlist)
AND Photos.Event_ID = $eid
GROUP BY Photos.Photo_ID
Note the join expression (I used inner join, assuming a matching record needs to exist in both tables) - it makes your where cleaner and easier to read.
Does this help:
$result= mysql_query("SELECT Photos.Filename, Photos.Filetype
FROM Photos, PhotoUserTags
WHERE PhotoUserTags.User_ID IN ($friendlist) && PhotoUserTags.Photo_ID = Photos.Photo_ID && Photos.Event_ID = $eid GROUP BY Photos.Photo_ID");

Categories