How to use find_in_set with join in codeigniter - php

I have 4 tables, and I want to fetch data from all the tables, I can do this by fetching data one by one from each table but I want to do it by using JOIN.
Main Table (which contains ids of other table data)
2, 3, 4 tables
now I want to fetch these fields.
from Table 1 (Main Table) - franchise_name, franchise_phone
from Table 2 (State Table) - state_name
from Table 3 (City Table) - city_name
from Table 4 (Area Table) - area_name
the first table contains ids of everything which I need to fetch from other tables.
but area_id in the main table is inserted as a string in the same row separated by (,) in field franchise_area.
I tried using FIND_IN_SET but did not work.

Read all 1-1 referred data using Join, cycle through data exploding area_id column
area_id -------> ($value = explode($row->area_id, ',')
then read data from database and insert into response array (or object).
Of course all of this operation must be done into the model...

Related

Implementing One to One and One to Many Query together in SQL

I have the following tables (Have only included necessary columns) which I'm looking to perform a query on. Some notes:
1) Table 1 has a one-one relationship with Tables 2 & 3, with the common key being menu_id.
Tables 4-6 are a little more complicated:
2) Table 1 has a one to many with table 4, so one menu can have many categories.
3) Table 4 has a one to many with table 5, so one category (Out of multiple above) can have many items.
4) Table 5 has again a one to many with table 6, so one item can have many subitems.
Table 1: -- user_menu --
menu_id
Table 2: -- menu_details --
menu_id
Table 3: -- menu_times --
menu_id
Table 4: -- menu_categories --
menu_category_id
menu_id
Table 5: -- menu_items --
menu_item_id
menu_category_id
Table 6: -- menu_subitems--
menu_subitem_id
menu_item_id
Question: I need a sql query which will fetch the all associated data from the tables (All columns, I haven't included them here, just the primary key rows) for a specific menu_id on table 1. That seems simple enough, but I'm struggling a little on the one to many part and getting that data in the same query.
I'm expecting something like this. Where menu_id = 2, it will fetch the associated row data (all columns). I've shortened the key names to fit.
user_menu | menu_details | menu_times | menu_categories | menu_items | menu_subitems
-------------------------------------------------------------------------------------
menu_id=2 - menu_id=2 - menu_id=2 -< cat_id=1 -< item_id=1 subitem_id=1
cat_id=2 -< item_id=2 -< subitem_id=2
cat_id=3 item_id=3 subitem_id=3
item_id=4 -< subitem_id=4
item_id=5 -< subitem_id=5
subitem_id=6
subitem_id=7
(I've shortened above. The proper names are in the first list, so please use those).
The ID's refer to the primary key rows I need the associated column data for. To clarify again If I were to query for menu_id = 2, I will get the menu_id = 2 row from table 2 & 3. I will also get the categories WHERE menu_id = 2 in the menu_categories table, the item_id rows where menu_category_id = x in the menu_item table, and the subitem rows where item_id = x from the menu_item table, in the subitem table.
I plan on copying the result to an array and passing that back. Just need the query bit (I'm assuming join but I'm not sure which is relevant here).
Thanks!
Yes, you can just use join, joining them using the key references should output it like that:
select A.menu_id, B.menu_id, C.menu_id, D.menu_category_id, E.menu_item_id,
F.menu_subitem_id
from user_menu A
join menu_details B on A.menuid = B.menuid
join menu_times C on B.menuid = C.menuid
join menu_categories D on C.menuid = D.menuid
join menu_items E on D.menu_category_id = E.menu_category_id
join menu_subitems F on E.menu_item_id = F.menu_item_id
where A.menu_id = 2

Table Name stored in column used as part of query?

I cant seem to find information related to this question.
I have four tables: pages, items, linktable, datatable
The pages table has a ID that links to the Items table.
The items table has an ID and Table Name field and ID that reference the table which has the actual data for the item.
aka:
Pages_Table:
pg_id
pg_title
Items_Table:
pg_id
item_type
item_id
link_table:
item_id
data_id
data_table_name
I need select data based on the data_table_name which varies, there are 10 different data_tables
I cant seem to find anything related to incorporating this into a SINGLE Query.
With multiple queries obviously not an issue. Essentially its selecting a database table dynamically to be included in the query.

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

codeigniter db->select handle mysql joins automaticly

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

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);

Categories