codeigniter db->select handle mysql joins automaticly - php

table
ID|owner_id|work_id|lorem|etc|
1 |00123 | 00213 |XXXXX|XXX|
2 |00124 | 00213 |XXXXX|XXX|
owner_id (fk) owners.id (owners[id,name,etc])
work_id (fk) work.id (work[id,name,etc])
question is can I set codeigniter that when I
select(table.*,work.name as work,owners.name as owner) from table
it automatically handle joins since that table already contain the fk-ref ? or I must include join('owner','owner.id=table.owner_id) ?
actually all what I want is that when I select a table that contains a fk this fk column is replaced with one column from ref row by just passing the column name on ref table without having to worry about creating a specific function in my module for that each query.
My current solution:
was to create a view for each table that contain a relation and replace all fk columns with desired ref value, but since i have 6 tables 5 of them with fk,i now have 6 tables and 5 view (11 tables)in db which is really kind confusing for me, so any smarter way to do this ?

I think you are making some confusion on what FK is and what it does within a table.
FK constraint grants data integrity when it's present and relates data within tables. It doesn't join anything.
If you want to select records across related tables, you either use a
SELECT * FROM table1,table2 WHERE table1.K1 = table2.FK1
or
SELECT * FROM table1 JOIN table2 ON table1.K1 = table2.FK1
AND YES, you need to tell CodeIgniter to do those queries

Related

How To Retrieve Columns from multiple tables

I have created two separate tables.
Table 1 (username,email,gender,age)
Table 2(taskname,description,createdon,duedate,workstatus).
Now I want to create a
table 3 (taskname,description,createdon,duedate,staffs,workstatus)
where staffs will show all the registered members' name and admin can select multiple users to allocate in a task.
I am a premature php learner.
Will anyone help me out to solve the problem,please ?
First of all, create two primary keys as user_id and task_id in table 1 and table 2 respectively. Once you are done with it, create table 3 with fields user_id and task_id as two foreign keys referencing table 1 and table 2 respectively and your requirement should get fulfilled.

PHP + Mysql: dynamic table name from first query for execution of second query

I have three tables, the first is a table storing applications, the second is a table storing different online forms (different types of applications), the third is a table that stores actual form data:
TABLE applications=========
-applicationID (PK)
-formID (FK)
-formRecordID
====================
TABLE forms=========
-formID (PK)
-formName
-tableName (could be 'form_businessLicense','eventLicense',etc)
====================
TABLE form_businessLicense=====
-recordID (PK)
-dateSubmitted
-(a whole bunch of other data)
===============================
"formRecordID" points to "recordID" in "form_businessLicense" or "eventLicense". Since it could reference any table, it can't be a foreign key. So instead I grab the tableName from the "forms" table, then build a query to get all the application data from, say "form_businessLicense".
So I need to get data from, say, all applications plus a bit of data from the application form filled out (ex:form_businessLicense). I'm just going to paste my code (I'm actually querying all applications in a given set of IDs):
$applications = $this->selectAll(
"SELECT applicationID, formName, tableName, fieldIdentifier, formRecordID, dateSubmitted, DATE_FORMAT(dateSubmitted,'%c/%e/%Y') AS dateSubmittedFormat
FROM applications AS a
JOIN forms AS f
ON a.formID = f.formID
WHERE a.applicationID IN (".$applicationIDs.")
ORDER BY dateSubmitted ASC"
);
for($a=0;$a<count($applications);$a++){
$form = $this->select("SELECT ".$applications[$a]['fieldIdentifier']." AS identifierName
FROM ".$applications[$a]['tableName']."
WHERE recordID = ".$applications[$a]['formRecordID']
);
$applications[$a]['identifierName'] = $form['identifierName'];
}
Is there any way to merge these two queries into one so I don't have to loop over all results and run a separate query for each result? I feel like I could maybe do this with a JOIN but I'm not sure how to reference the "tableName" and "formRecordID" for use in the same SQL statement.
You need to apply join to three tables, and select count(PK) of third table while adding a group by clause for the PK of third table.
Note: PK used for Primary Key

DB Design; or Conditional Selects with json data

I have a DB with several tables that contain basic, static ID-to-name data. 2 Columns only in each of these reference tables.
I then have another table that will be receiving data input by users. Each instance of user input will have it's own row with a timestamp, but the important columns here will contain either one, or several of the ID's related to names in one of the other tables. For the ease of submitting and retrieving this information I opted to input it as text, in json format.
Everything was going great until I realized I'm going to need to Join the big table with the little tables to reference the names to the ID's. I need to return the IDs in the results as well.
An example of what a few rows in this table might look like:
Column 1 | Column 2 | Timestamp
["715835199","91158582","90516801"] | ["11987","11987","22474"] | 2012-08-28 21:18:48
["715835199"] | ["0"] | 2012-08-28 21:22:48
["91158582","90516801"] | ["11987"] | 2012-08-28 21:25:48
There WILL be repeats of the ID#'s input in this table, but not necessarily in the same groupings, hence why I put the ID to name pairings in a separate table.
Is it possible to do a WHERE name='any-of-these-json-values'? Am I best off doing a ghetto join in php after I query the main table to pull the IDs for the names I need to include? Or do I just need to redo the design of the data input table entirely?
First of all:
Never, ever put more than one information into one field, if you want to access them seperately. Never.
That said, I think you will need to create a full N:M relation, which includes a join table: One row in your example table will need to be replaced by 1-N rows in the join table.
A tricky join with string matching will perform acceptably only for a very small number of rows, and the WHERE name='any-of-these-json-values' is impossible in your construct: MySQL doesn't "understand", that this is a JSON array - it sees it as unstructured text. On a join table, this clause comes quite naturally as WHERE somecolumn IN (1234,5678,8012)
Edit
Assuming your Column 1 contains arrays of IDs in table1 and Column 2 carries arrays of IDs in table2 you would have to do something like
CREATE TABLE t1t2join (
t1id INT NOT NULL ,
t2id INT NOT NULL ,
`Timestamp` DATETIME NOT NULL ,
PRIMARY KEY (t1id,t2id,`Timestamp`) ,
KEY (t2id)
)
(you might want to sanity-check the keys)
And on an insert do the following (in pseudo-code)
Remember timestamp
Cycle all permutations of (Column1,Column2) given by user
Create row
So for your third example row, the SQL would be:
SELECT #now:=NOW();
INSERT INTO t1t2join VALUES
(91158582,11987,#now),
(90516801,11987,#now);

What is the advantage of relationships between tables in sql?

I made three tables.
Table1=users.And the column names are userid (auto_increment) and username.
Table2=hobbies. column names are hobbyid (auto_increment) and hobbyname.
Table3=users_hobbies. column names are FK_userid and FK_hobbyid.
Now whenever I register new user and his/her hobbies from a html form, I select the
corresponding userid and hoobyid that is generated from table 1 and table 2
and insert them to table 3 using query
So what is the use of relationship, if I create it between table 1 and 3 and table 2 and 3?
Will the corresponding userid and hobbyid automatically go to table 3 without using query?
No, the userid and hobbyid won't go automatically anywhere.
The major point of relationships or rather constraints is to enforce data integrity. That means you shouldn't be able to add an entry containing id 2, 2 into the users_hobbies table without a user with id 2 and a hobby with id 2.
In order to keep this integrity you can also specify cascadings. (Depending on the Database system, I hardly work with mysql, so I am not sure about that).
That means, you can specify that all users_hobbies for user with id 1 are deleted if the user himself is deleted.

PHP select row from db where ID is found in group of IDs

I have 3 employers IDs: 1, 2 and 3. I am generating tasks for each one by adding a line in database and in column "for_emp" I insert IDs I want to assign this task for and could be all 3 of them separated by comma. So let's say I got a task and "for_emp" is "1,2,3", the employers IDs. If I would like to select all tasks for the ID 2, will I be able to select from the row that has "1,2,3" as IDs and just match "2" there ? If not, how do you suggest I insert my emp IDs into one row in database ? The db is MySQL.
Any ideas ? Thanks.
Don't do it like that, you should normalize your database.
What you want to do is have a table such as task, and then task_assignee. task_assignee would have fields task_id and user_id. If a task has eg. three assignees (IDs 1, 2 and 3), then you'll create three rows in the task_assignee table for that one task, like this:
+--------+---------+
|task_id | user_id |
+--------+---------+
| 1 | 1 [
| 1 | 2 [
| 1 | 3 [
+--------+---------+
Then it's just a simple matter of querying the task_assignee table to find all tasks that are assigned to a given user.
Here's an example of how to get all the tasks for user_id 2:
SELECT t.* FROM task AS t INNER JOIN task_assignee AS ta WHERE ta.user_id = 2
EDIT.
Just as a related note, even if you didn't do it the right way (which I described in my answer previously), doing it with hacks such as LIKE would still be far from the optimal solution. If you did store a list of comma-separated values, and needed to check if eg. the value 2 is in the list, you could use the MySQL's FIND_IN_SET function:
SELECT * FROM task WHERE FIND_IN_SET(2, for_emp)
But you shouldn't do this unless you have no choice (eg. you're working with someone's shitty DB design), because it's way more inefficient and won't let you index the the employee ID.
The following query should do what you want:
SELECT * FROM tasks WHERE for_emp LIKE '%2%';
However, be aware that that would also match employers 12, 20, 21 etc; so take care if you expect you might end up in double-digits.
However, the other answers about renormalising your database are definitely preferable.
You're doing it wrong. Create a relation table with two fields: employee id and task id. If one task should be assigned to three employees, insert three rows in the relation table.
You then use JOIN to join the task, employee and relation tables.
then its no proper relation...
I would suggest a "mapping table" for the n:m relation
employee
id
task
id
employeetask
task_id
employee_id
Make a table for your employers. Insert your three rows in it.
Then make a table for mapping tasks to employers. If a task is assigned to three employers, insert three rows into this table. This is basic entity-relation work.
I would make 2 different tables.
1 with employees, and 1 with tasks.
then make another table which combines the two tables, I will call it Assigned Tasks.
Then in assigned tasks I make a assigned id, a employeenumber which is a FK to the employee table and a taskid which is a FK to the Tasks table.
If an employee has more than 1 task. Just insert another row in the assigned table. ;)
When its about Databases, try to think in solo entities! Combining those entities is able in antoher table.
sql example:
Select * from Assignedtasks where employeeID = 1 will give you all his/her tasks. :)
You could use a LIKE '%,2,%' clause in your SELECT statement.
eg:
SELECT * FROM table where for_emp LIKE '%,2,%'
However performance of such non-sargable queries is usually quite bad.
I would suggest that you insert a row each for each employee who is assigned to the task using a separate TASK_EMPLOYEE_MAPPING table with taskId, employeeId as a composite primary key.
With such a design, your query will be
SELECT * FROM TASK_EMPLOYEE_MAPPING WHERE employeeId = '2'

Categories