MySQL join for CodeIgniter - php

I have 2 tables. Table kind and table living.
In the table kind, it has id, kind_o & living_id while in living it has id & type.
Example data.
KIND
id kind_o living_id
1 dog 1
2 narra 2
LIVING
id type
1 animal
2 tree
How can I query in CodeIgniter if I want to return ex. SELECT * kind WHERE id = 1 and i want to return also all the data inside living table?
Example output:
id kind_o living_id living.id type
1 dog 1 1 animal
2 tree

Try :
$this->db->select('k.*,l.type');
$this->db->from('kind as k');
$this->db->join('living as l','l.id = k.living_id');
$this->db->where('l.id','1');//use Kind id Here you want to use.
$query = $this->db->get();
$this->db->last_query();
return $query->result_array();
See Document

select k.id as kind_id, k.kind_o, k.living_id, l.id as living_id, l.type FROM kind k join living l on (k.living_id=l.id);
Always prefer to select fields comma seperated then using select *.
select * usually takes time compared to query selecting all required feilds.

Related

I want to join 4 tables in codeigniter

Till know I join 3 table
$this->db->select('*');
$this->db->from('dispatch_challan');
$this->db->join('challan_bilties', 'dispatch_challan.disp_id = challan_bilties.challan_id');
$this->db->join('bilty', 'challan_bilties.challan_bilties_id = bilty.id');
$this->db->where('dispatch_challan.disp_ch_no',$disp_ch_no);
$query = $this->db->get();
return $query->result_array();
My output is like this after join table
In above image the Consignor and Consignee fetch id but i want name so i want to join 4th table i.e ts_users
In this table the full name of this Consignor and Consignee
ts_users table
user_id user_fullname user_remark
1 abc consignee
2 xyz consignor
3 pqr consignee
4 lmn consignor
I want to get full name based on Consignor and Consignee from 4th table(ts_users)
Since you don't really tell us where the consignor and consignee fields come from, you'll need to fill in the blanks (denoted as xxx below)
All you need is to join twice with the ts_users table. Add these:
$this->db->join('ts_users u1', 'xxx.consignor = u1.user_id');
$this->db->join('ts_users u2', 'xxx.consignee = u2.user_id');
Since you'll be joining twice with the same table, your resultset will be a bit confusing if you stick to select * so I'd recommend fetching only the fields you need. For instance:
$this->db->select('u1.user_id as consignor, u2.user_id as consignee, dispatch_challan.*, challan_bilties.*, bilty.*');
give it a shot and let me know if it works
This is how to join any number of tables in codeigniter without any problems:
$this->db->select("
$table_1.id AS table_1_id,
$table_1.whatever AS table_1_whatever,
$table_2.id AS table_2_id,
$table_2.whatever AS table_2_whatever,
$table_3.id AS table_3_id,
$table_3.whatever AS table_3_whatever,
$table_4.id AS table_4_id,
$table_4.whatever AS table_4_whatever,
");
$this->db->join($table_2, "$table_2.id = $table_1.table_2_id", 'left');
$this->db->join($table_3, "$table_3.id = $table_1.table_3_id", 'left');
$this->db->join($table_4, "$table_4.id = $table_1.table_4_id", 'left');

MySQL count datas with row values without new query loop

I've 4 table for a newsletter. Newsletters, Subscribers, Subscriber Groups and Selected Subscriber Groups. I've choose subscriber groups in campaign edit area, and its save selected groups to tbl_newsletter_groups table like;
tbl_newsletters
NID title details
1 text 1 content 1
2 text 2 content 2
tbl_subscriber_groups
GID group_name
5 group 1
6 group 2
tbl_subscribers
SID GID email name
10 5 sub1#mail.com sub1 name
11 6 sub1#mail.com sub1 name
tbl_newsletter_groups
NGID NID GID
15 1 6
16 1 6
17 1 6
I want to show total selected subscriber count when I list newsletters in my page. My soulution works fine, Im looking for simple and clearly statement, there any faster way available like in single newsletter list statement?
Here my own count style (yes I know its too bad and long way);
$subGID = array();
$list = $myconn->query("SELECT * FROM tbl_newsletters");
while($listRs = $list->fetch_assoc()){
$grps = $myconn->query("SELECT * FROM tbl_newsletter_groups WHERE NID=". $listRs['NID'] ."");
while($grpsRs = $grps->fetch_asscoc()){
$subGID[] = $grpsRs['GID'];
} $grps->free();
$subs = implode(" OR GID=",$subGID);
$count = mysqli_num_rows($myconn->query("SELECT ID FROM tbl_subscribers WHERE GID=". $subs));
echo('Total Selected Subscriber: '.$count);
} $list->free();
Thanks.
The search term you want is "set-based logic".
Your thinking is sound: you need everything from tbl_newsletters, then you need to count results from tbl_subscribers, but in order to get those you need information from tbl_newsletter_groups.
In SQL, that's an indication you want a join. You've already discovered the conditions you need, you just don't know the syntax. A reference manual can help there.
Now you'll have a bunch of records, which you need to smash into a smaller number of records. You need aggregation functions and a GROUP BY clause.
So here's the final query:
SELECT n.NID, n.title, n.details, COUNT(s.SID)
FROM tbl_newsletters AS n
JOIN tbl_newsletter_groups AS g ON n.NID = g.NID
JOIN tbl_subscribers AS s ON g.GID = s.GID
GROUP BY n.NID

Use commaseparated mySQL column value in LIKE

I have column in my database named as foodtype . Table name is restaurant and the column foodtype has comma separated values (as Indian,Chinese).
Now, when a person select Chinese then the i want mysql query should return restaurant where foodtype is Chinese.
Query should become like as below:
SELECT * FROM restaurant WHERE cityname='Chicago' and foodtype
LIKE ('%Chinese%')
And when a person select Indian then the i want mysql query should return restaurant where foodtype is Indian.
Query should become like as below:
SELECT * FROM restaurant WHERE cityname='Chicago' and foodtype
LIKE ('%Indian%')
And when a person select Indian and Chinese both then the i want mysql query should return restaurant where foodtype is Indian and Chinese.
Query should become like as below:
SELECT * FROM restaurant WHERE cityname='Chicago' and foodtype
LIKE ('%Indian%,%Chinese%')
Please let me know how can i achieve this.
Use FIND_IN_SET()
SELECT *
FROM restaurant
WHERE cityname='Chicago'
and find_in_set(foodtype, 'Indian') > 0
and find_in_set(foodtype, 'Chinese') > 0
But actually you are better off by chaning your table structure. Never, never, never store multiple values in one column!
To achieve that you can add 2 other tables to your DB
foodtypes table
---------------
id
name
restaurant_foodtypes
--------------------
restaurant_id
foodtype_id
Example data:
foodtypes
id | name
1 | chinese
2 | indian
restaurant_foodtypes
restanrant_id | foodtype_id
1 | 1
1 | 2
Then you can select restaurants having both foodtypes like this
select r.name
from restaurants r
join restaurant_foodtypes rf on rf.restaurant_id = r.id
join foodtypes f on rf.foodtype_id = f.id
where f.name in ('indian','chinese')
group by r.name
having count(distinct f.name) = 2

Advanced mysql queries, fetching from several tables and rows at once. Joins?

I'm currently working on a project where I have information stored in several tables that all connect to each other. I believe that the table and column format is logical and the best choice. The problem though, is that I don't have enough knowledge to build queries advanced enough to fetch all the information I need.
The main table is ab_ads, where advertisements are stored. These ads can be assigned several formats (ie. 250x360, 980x120 etc), and you can also select the region where they should be showing (ie. Skåne, Stockholm, Kalmar, Dalarna, Jämtland etc).
This is how I store my data. I'm not showing all tables but I hope this is sufficient.
Advertisements column (ab_ads): (There are more columns but they are not relevant)
ID orgnum company_name title content link
1 556664-7524 Company Inc Lorem ipsum Lorem ipsum URL
Advertisement states (ab_ads_states):
ID adID stateID
1 1 2 // Skåne
2 1 5 // Kalmar
3 1 8 // Stockholm
4 1 10 // Värmland
5 2 2 // Skåne
6 2 5 // Kalmar
7 3 8 // Stockholm
8 4 10 // Värmland
Advertisement formats (ab_ads_formats)
ID adID formatID
1 1 1 // 250x360
2 1 2 // 980x120
3 2 1 // 250x360
4 3 2 // 980x120
Formats table (ab_formats)
ID name width height
1 Format 1 250 360
2 Format 2 980 120
So, I have two flash banners both are supposed to call a PHP-script which in turn is supposed to deliver an XML-file back with all the results.
I know how to select data from different tables, but I've never worked with selecting multiple rows from another table and merging them into one, which I suppose is that I need to do here. I'm very thankful for any help I can get.
The flash banners will send two parameters to the PHP file, stateID and formatID. Which means I have to SELECT ad WHERE state = param AND format = format. But since I store multiple entries for the ad states I don't know how to do it.
EDIT:
I would also like to fetch the format names in the query and get them in the following format: "Format 1,Format 2" in a column named "formats". I guess this would require some kind of join?
Thanks in advance!
I think this will work:
select ab.name as formats, aa.* from ab_ads as aa
inner join ab_ads_states as aas on aa.id = aas.adid and aas.stateId = stateIdParam
inner join ab_ads_formats as aaf on aa.id = aaf.adid and aaf.formatId = formatIdParam
inner join ab_formats as ab on aaf.formatid = ab.id
Edit:
I'm not very good with mySql, and don't have anything to test this on, but I think group_concat may be what you are looking for. If so, it will probably look something like this:
select group_concat(ab.name separator ", ") as formats from ab_ads aa
inner join ab_ads_states as aas on aa.id = aas.adid and aas.stateId = 2
inner join ab_ads_formats as aaf on aa.id = aaf.adid and aaf.formatId in(1,2)
inner join ab_formats as ab on aaf.formatid = ab.id
group by ab.id
Please try below SQL:
SELECT count(aaf.ID) AS TotalFormat,
group_concat(ab.name) AS formats
FROM ab_ads aa
INNER JOIN ab_ads_states AS aas ON aa.ID = aas.adID
AND aas.stateID = 2
INNER JOIN ab_ads_formats AS aaf ON aa.id = aaf.adID
AND aaf.formatID in(1,2)
INNER JOIN ab_formats AS ab ON aaf.formatID = ab.ID
GROUP BY aaf.adID HAVING TotalFormat >=2
SQL Demo: http://sqlfiddle.com/#!2/9f0ab/10

sql statement to alphabetize and count

Here is the mySQL I got
id terms
1 a
2 c
3 a
4 b
5 b
6 a
7 a
8 b
9 b
10 b
I want to get an alphabetized list sorted by count as follows
terms count
a 4
b 5
c 1
What mySQL statement do I need for that?
I believe something like this will work:
SELECT terms, COUNT( id) AS count
FROM table
GROUP BY terms
ORDER BY terms DESC
Read : GROUP BY (Transact-SQL)
Groups a selected set of rows into a set of summary rows by the values of one or more columns or expressions in SQL. One row is returned for each group. Aggregate functions in the SELECT clause list provide information about each group instead of individual rows.
You just need to apply group by clause for getting result
select terms, count (id) as count from table
group by terms
order by terms
I had a very similar need for a used record store to display artists in stock alphabetically with their count in parenthesis e.g.:
Smokey Robinson and The Miracles (2) | Sonic Youth (2) | Spoon (3) | Steely Dan (1) | Stevie Wonder (2) | Sufjan Stevens (1) |
Note that I used SELECT DISTINCT when pulling from my table "records". Here are the relevant code snippets:
//QUERY
$arttool = mysql_query("SELECT DISTINCT * FROM records GROUP BY artist ORDER BY artist ASC");
//OUTPUT LOOP START
while($row = mysql_fetch_array($arttool)){
//CAPTURE ARTIST IN CURRENT LOOP POSITION
$current=$row['Artist'];
//CAPTURING THE NUMBER OF ALBUMS IN STOCK BY CURRENT ARTIST
$artcount = mysql_num_rows(mysql_query("SELECT * FROM records WHERE artist = '$current'"));
//ECHO OUT.
echo $current . "($artcount)";
The actual code in my site is more complicated, but this is the bare bones of it. Hope that helps...

Categories