MYSQL Inner Join Two Tables Same Column name Different Value [duplicate] - php

This question already has answers here:
How to resolve ambiguous column names when retrieving results?
(11 answers)
Closed 2 years ago.
I have two tables like this:-
Tablea
-------
id|Comp_name|
1 |abc |
Tableb
--------
ids|id|Comp_name|
2 |1 |def|
I'm trying to inner join these two table into one with query like this
SELECT * FROM tablea
INNER JOIN tableb ON tablea.id=tableb.id
The result is like this
id|Comp_name|ids|Comp_name|
1 |abc |2 |def|
.
How To separate Comp_name value into php ?
I tried code like this but fail:-
foreach($query->result() as $row){
echo '<tr class="'.$class.'">
<td>
'.$row->Tablea.Comp_name.'
</td>
<td>
'.$row->Tablea.Comp_name.'
</td>

An alias can be used in a query select list to give a column a different name.
For more info Click here.
SQL Query looks like
SELECT tablea.id,tablea.Comp_name AS compname_a, tableb.*
FROM tablea
INNER JOIN tableb ON tablea.id=tableb.id
PHP
<?php foreach($query->result() as $row):?>
<tr class="<?php echo $class?>">
<td><?php echo $row->compname_a ?></td>
<td><?php echo $row->Comp_name ?></td>
</tr>
<?php endforeach;?>

For your desired output, you just need to use alias for getting same column name value from two tables.
Modified Query:
SELECT tablea.id, tablea.Comp_name as FirstVal,
tableb.ids, tableb.Comp_name as SecondVal
FROM tablea
INNER JOIN tableb ON tablea.id=tableb.id
Than you can get in php something like:
$row->FirstVal // for ist value
$row->SecondVal // for second value
You can also explore more: MYSQL Alias

You can try the following:
SELECT id, tablea.Comp_name as A_Comp_name, ids, tableb.Comp_name as B_Comp_name
FROM tablea
INNER JOIN tableb ON tablea.id=tableb.id
And the result will be something like this:
id|A_Comp_name|ids|B_Comp_name|
1 |abc |2 |def |

Use alias for this type of situation.
query:
SELECT tablea.Comp_name as company1, tableb.Comp_name as company2
FROM tablea
INNER JOIN tableb ON tablea.id=tableb.id

Related

Join two tables using php

I have no idea with joins and I am really having a trouble getting the logic. Can anyone please help me?
Here is my table Announcements:
AnnouncementID Subject Header Status
---------------------------------------------------
1 Peter Header 2 Publish
2 2x2 Header 3 Draft
3 Resignation Header 4 Publish
And here is another table ReadAnnouncements:
AnnouncementID Username Status
---------------------------------------------
1 User 1 Read
2 User 2 Read
2 User 3 Read
I want my result to be
AnnouncementID Username Status Header Subject
---------------------------------------------------------------
1 User 1 Read Peter Header 2
2 User 2 Read 2x2 Header 3
2 User 3 Read 2x2 Header 3
Please teach me how I am really confused been trying this for two days already.
<?php
$sql=" SELECT a.AnnouncementID,a.Created,r.Username,a.Status,a.Header,a.Body from Announcements a join ReadAnnouncements r using(AnnouncementID) WHERE a.Status = 'Publish'";
$result = mysqli_query( $conn,$sql);
while($rows = mysqli_fetch_array($result)){
$time = date('h:i:s a',strtotime($rows['Created']));
$date = date('Y-m-d',strtotime($rows['Created']));
if($rows['ReadStatus'] == 'Unread'){
echo '
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
';
}else{
echo '<strong>
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
</strong>';
}
}
?>
I want to select all rows from table announcements that are only Published and classify them if they are read or unread based on username and announcement id.
You can use the below query to get the result.
select a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r on r.AnnouncementID=a.AnnouncementID
Joins are pretty easy, check this explanation.
In your case, you can do something like this:
SELECT A.AnnouncementID, A.Username, R.Status, A.Header, A.Subject FROM Announcements A join ReadAnnouncements R USING(AnnouncementID)
You can use inner join. The INNER JOIN keyword selects records that have matching values in both tables.
SELECT a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r using(AnnouncementID)
Use JOIN clause to combine rows from two or more tables in a database, based on a related column between them ( in your case, AnnouncementID ).
When combine data from 2 tables, you have a few combinations possible:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
(source: https://www.w3schools.com/sql/sql_join.asp)
Using your database schema, you should use:
select * from Announcements as A INNER JOIN ReadAnnouncements as RA ON A.AnnouncementID RA.AnnouncementID
You don't mention which DBMS you are using, so SQL query above may differ.

How to insert data with this SQL relationship?

I am trying to get all records from teacher tables row teacher_id, into timetables table row teachers_id, by using right join, i tried this code but data was not inserted in timetables coloumn teacher's id.
TimeTable looks like this:
teacher_id,student_id,class_id;
Here is my query:
select timetable.* from timetable right join teachers on
timetable.teacher_id = teachers.teacher_id;
Sample data:
Teachers table:
**teacher_id | teacher_name**
1 | asa
2 | saa
3 | ddd
4 | eee
Timetable table:
**teacher_id | class_id | student_id**
As you said in question, you like to get all records data from teacher tables row.
So if you like to see all data in teachers table use this:
select teachers.* from timetable right join teachers on
timetable.teacher_id = teachers.teacher_id;
In another part you said, you can't see any data inserted in timetable, if you like to see the rows in timetable, use it :
select timetable.* from timetable right join teachers on
timetable.teacher_id = teachers.teacher_id;
and if you like to see both use it:
select timetable.*,teachers.* from timetable right join teachers on
timetable.teacher_id = teachers.teacher_id;
try below : you write same table twice that's why error occured:
select teachers.teacher_id from teachers left join timetable on
timetable.teacher_id = teachers.teacher_id;

PHP - Getting wrong result when selecting from two tables

I have been trying to get some results when selecting combo boxes.
here is my query:
$strSQL = "SELECT * FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
This query is returning all the studentresult.id = 2 where studentresult.id is primary.
This is the php code:
<td><div align="center"><?=$objResult["id"];?></div></td>
<td><div align="center"><?=$objResult["studentid"];?></div></td>
<td><?=$objResult["subjectid"];?></td>
<td><?=$objResult["marks"];?></td>
<td><div align="center"><?=$objResult["term"];?></div></td>
<td align="right"><?=$objResult["year"];?></td>
<td align="right"><?=$objResult["rank"];?></td>
The id is taken from student table rather than being taken from studentresult table. Can someone help me with this.
EDIT 1:
The id is present in both tables
EDIT 2:
Student result:
id| StudentID| SubjectID| Marks| Rank| Term| Year
Student:
id| Roll Num| class| Name| Surname
Thanking You In Advance
Bhaamb
$strSQL = "SELECT *,studentresult.id as stid FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
Then
<div align="center"><?=$objResult["stid"];?></div>
You Better specify the column names instead of (*) from both the tables alias the column names to avoid column name conflicts if both are same and also try to use Join(Inner or Left) based on the need.
for example, some thing like this:
SELECT S.id AS student_id, SR.id as StudentResultId, S.class, s.year
FROM studentresult AS SR
INNER JOIN student AS S
WHERE SR.studentid=S.id and S.class='$classes' and s.term='$term'and SR.studentid=s.id and s.year='$year'
First of all, why do you use this twice in the where clause?
studentresult.studentid=student.id
Please define all needed columns explicitly while joining tables having the same column names, e.g.
SELECT studentresult.id as sr_id, student.id as s_id ... FROM ...
and change it in your php code:
<?=$objResult["sr_id"];?>

Hyphen-delimited values and LEFT_JOIN

I have a row with some values hyphen-delimited:
table: live_customers
row: areas
id | areas
1 | 10-20-30
2 | 40-50-60
...
Using this...
LEFT JOIN $table5 AS table5 ON live.areas REGEXP CONCAT('(^|-) ?',table5.id,' ?($|-)')
My results looks like:
(tab id:1) area: 10
(tab id:1) area: 20
...
(tab id:2) area: 40
...
But i expect:
(tab id:1) area: 10,20,30
(tab id:2) area: 40,50,60
How could i solve that?
EDIT:
The full query looks like:
SELECT live.*,
live.id AS lid,
table1.id, table1.value AS tn_val,
table2.id, table2.value AS tp_val,
table3.id, table3.value AS ht_val,
table5.id, table5.value AS ar_val
FROM $dblist AS live
LEFT JOIN $table1 AS table1 ON live.town = table1.id
LEFT JOIN $table2 AS table2 ON live.htype = table2.id
LEFT JOIN $table3 AS table3 ON live.ht = table3.id
LEFT JOIN $table5 AS table5 ON live.areas REGEXP CONCAT('(^|-) ?',table5.id,' ?($|-)')
ORDER BY live.id ASC
PHP echoes:
...
if ($post['areas']){ // Debugging areas stuff
echo '<strong>'.$_areas.': (ar_val)</strong> '.$post['ar_val'].'<p>';
echo '<strong>'.$_areas.': (areas)</strong> '.$post['areas'].'<p>';
}
...
EDIT2:
It's quite hard for me to explain my issue in English, but i'm trying the best i can :)
in the table "live_customers" i does have this:
id | areas
1 | 10-20-30
2 | 40-50-60
...
in the table "areas" (that is a completely different table):
id | value
38 | Zone1
39 | Zone2
40 | Zone3
...
In the SQL query you see just tables variables because i previousvly declared them at the top of page:
$table5 = 'areas';
$dblist = 'live_customers';
etc..
Solution
Thanks anyone for their answers and for let me know "GROUP_CONCAT".
Here is my solution:
SELECT live.*,
live.id AS lid,
table1.id, table1.value AS tn_val,
table2.id, table2.value AS tp_val,
table3.id, table3.value AS ht_val,
table5.id, GROUP_CONCAT(table5.value) AS ar_val
FROM $dblist AS live
LEFT JOIN $table1 AS table1 ON live.town = table1.id
LEFT JOIN $table2 AS table2 ON live.htype = table2.id
LEFT JOIN $table3 AS table3 ON live.ht = table3.id
LEFT JOIN $table5 AS table5 ON FIND_IN_SET(table5.id, REPLACE(live.areas, '-', ','))
GROUP BY live.id
Result is what i expected ^^
Take it together with GROUP_CONCAT()
First thing to say is that your schema violates First Normal Form (1NF) in that the column areas is not atomic. You should not be putting 3 different values in one column.
Next you say you have a table called live_customers with a row called areas. This is nonsense. Rows do not have names, columns do. You show a bit of table with 2 columns id and areas. What table is this?
Next in the query there is no mention of a table called live_customers.
Next, if there is a column called areas in the table with the alias of live, then the output should contain that column since you are selecting live.*. That being the case, your results cannot be what you showed us, since it would contain a results column with data like 10-20-30
Finally those cannot be the results of the posted query since I can see a results column of lid specified.
If you would care to take some time over ensuring that the questionyou post makes sense, then you might get a reasonable answer.

trying to output the correct value from SQL query from comparing a different table

I'm very new with SQL and need assistance on how I can accomplish this task using the correct query.
I have 2 tables that I need to use. Table "TB1" has:
id Name
1 bob
2 blow
3 joe
table "TB2" has:
compid property
1 bob
2 blow
I am trying to get which compid is missing in "TB2" and insert it from "TB1"
the query I am doing is:
SELECT id, name from TB1, TB2 where id <> compid
what I get is 2 ouputs of Id 1, and 2, and 3 outputs from id 3. by using php:
for($i=0;$i <= mysql_num_rows($comp)-1; $i++)
{
echo mysql_result($comp, $i, 0)."<br>";
}
and I expected the ouput 3 but instead got this:
1
1
2
2
3
3
3
I understand its comparing all the rows within the table but is there a way to achieve what I am looking for?
Thanks for your time.
You are performing an implicit Cartesian JOIN which results in every row against every other row. You need to specify what attribute JOINs the two tables.
Using implicit syntax (not recommended):
SELECT id, name
FROM TB1, TB2
WHERE id <> compid
AND TB1.Name = TB2.property <-- Column join
Using explicit syntax:
SELECT id, name
FROM TB1
JOIN TB2
ON TB2.property = TB1.Name <-- Column join
WHERE id <> compid
To accomplish your goal you would need something along the lines of:
SELECT TB1.id, TB1.name
FROM TB1
LEFT JOIN TB2
ON TB2.property = TB1.Name
WHERE TB2.compid IS NULL
See it in action
It's best practice to always alias the columns you select to prevent ambiguity.
To select it you can do:
SELECT *
FROM TB1
WHERE id NOT IN (
SELECT compid
FROM TB2
);

Categories