How to do INNER JOIN correctly ? mysql - php

I have two tables :
table1 :
businessId | businessName | categoryId
1 name1 355
2 name2 451
. . .
. . .
table2 :
categoryId | bussinessId
56 2
99 2
100 8
. .
. .
so the business could be belongs to several categories (one to many relationship).
I want to get the business name by the categoryId.
I am using this query :
SELECT table1.businessName FROM table1 INNER JOIN table2
WHERE
table2.businessId = table1.businessId AND table2.categoryId = $_GET['categoryId'];
this query just get the business whose belong to specific categoryId according to tabel2 but ignore the relation at table1.
How could I improve the query to check also the relation between the categoryId and the business at table1 ?
I know that categoryId col at table1 should be immigrate to table2 , but now I could not do this ?
actually I tried also this query :
SELECT table1.businessName FROM table1 INNER JOIN table2
WHERE
(table2.businessId = table1.businessId AND tabl2.categoryId = $_GET['categoryId'])
OR table1.businessId = $_GET['categoryId' ;
but this doesn't work good! it brings many rows !

It's usually neater to have the join condition in the on clause. If you have multiple join conditions (business and category IDs), you can just use and to have them both:
SELECT table1.businessName
FROM table1 t1
INNER JOIN table2 AS t2 ON t2.businessId = t1.businessId AND
t2.categoryId = t1.categoryId
WHERE t2.categoryId = $_GET['categoryId'];

Try as below , so first join the tables with the common key and then filter out the data using the where
SELECT
table1.businessName FROM table1
INNER JOIN table2 on table2.businessId = table1.businessId
where
table2.categoryId = $_GET['categoryId'] ;

(untested) This query also show you data of the relationship of a categoryId with a businessId in table1.
I've chosen for a UNION because I assumed it could be possible that in table1 a link between category and a business is made which
isn't included in table2
select businessName
from table1
where categoryId = $_GET['categoryId']
UNION ALL
select t1.businessName
from table1 as t1
inner join table2 as t2 on t2.categoryId = t1.categoryId AND
t2.businessId = t1.businessId
where t2.categoryId = $_GET['categoryId']

Related

PHP SQL get data from 2 tables and output wanted information

i am trying to achieve the following result. (i am sorry for the horrible explanation but i find it very hard to explain :P)
I need data from 2 tables.
Table1
id, table2_id, user_id
Table2
id, Name
Table1 example information
ID 1 Table2_id 1 user_id 3
ID 2 Table2_id 2 user_id 3
ID 3 Table2_id 5 user_id 3
Table2 Example Information
ID 1 Name TEST
ID 2 Name Hello
ID 3 Name Helpme
ID 4 Name Please
ID 5 Name IamLost
i Would like to output everything tied user_id 3. This would be my ideal end result
TEST
Hello
IamLost
I have this as code
$id = "3";
$sth = $db->prepare("SELECT table2_id, user_id, naam FROM table1, table2 where user_id = $id ");
$sth->execute();
$result = $sth->fetchAll();
foreach( $result as $row ) {
echo $row['table2_id'] . ' ';
echo $row['naam'] . '<br>';
}
But this just outputs everything but then twice. like this
TEST
TEST
Hello
Hello
Helpme
Helpme
Please
Please
IamLost
IamLost
A LEFT JOIN should do the trick:
SELECT `table1`.`table2_id`, `table1`.`user_id`, `table2`.`name`
FROM `table1`
LEFT JOIN `table2`
ON `table1`.`Table2_id` = `table2`.`id`
WHERE `table1`.`id` = $id
MySQL JOIN Syntax
Use Joins in SQL.
The SQL Query should look like this:
SELECT T1.USER_ID, T2.NAME
FROM TABLE1 AS T1
JOIN TABLE2 AS T2
ON T1.TABLE2_ID = T2.ID
WHERE T1.USER_ID = 3
these two table must be related to each other. When you select , returned rows should be equal this two tables. This why we use table joins e.g
SELECT a.user_id,a.table_id,b.name FROM table1 as a, table2 as b
RIGHT OUTER JOIN table 1
ON b.ID = a.table2_id
AND table1.user_id = 3
I believe you just need to be more precise:
$sth = $db->prepare("SELECT table2_id, user_id, name
FROM table1
LEFT JOIN table2
ON table1.Table2_id = table2.id
WHERE user_id = $id ");
A simple right outer join will help you here.
SELECT * FROM table2
RIGHT OUTER JOIN table 1
ON table2.ID = table1.table2_id
AND table1.user_id = 3

how to count rows in table that has specific property in another table

table1
--------------
| sn | class |
--------------
table2
----------------
| id | student |
----------------
all are int as sn is table1 is linked to student in table2
sn, id are auto increasing. when inserting data to table2 student column is same as sn in table 1
now I want to select student in table2 but only those whose class in table1 is "3"
my syntax is thus;
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
so that i can count them by saying
$quantity = mysql_num_rows($count)
now my problem is if sql also have this whose keyword, or how do i go about this.
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
You need to join the tables in order to filter the results properly.
(1) This will give you the number of students for class 3.
$count = mysql_query(
'SELECT COUNT(t2.student)
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
AND t1.class = 3'
);
(2) This will give you all classes and the number of students for each.
$count = mysql_query(
'SELECT t1.class, COUNT(t2.student)
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
GROUP BY t1.class
ORDER BY t1.class'
);
(3) This will give you all classes and the students list.
$list = mysql_query(
'SELECT t1.class, GROUP_CONCAT(t2.student SEPARATOR ',')
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
GROUP BY t1.class
ORDER BY t1.class'
);
You should join those two tables and limit your result to those which have table1.class = 3
SELECT
student
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
If you want a count you could also do it through SQL by using aggregate function
SELECT
COUNT(student)
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3

Mysql multiple left joins on same table

I have a table with two fields that reference the ID of another table. I need to pull the name from the other table for both fields.
eg.
Table1
worker1 = 2 (2 is key to other table)
worker2 = 4
Table2
ID NAME
1 Bill
2 Fred
3 John
4 Paul
I need to get $worker1name = Fred and $worker2name = Paul.
So I will be saying something like:
SELECT xxx, NAME?, NAME? FROM Table1
LEFT JOIN Table2 AS p1 ON Table1.worker1 = Table2.ID
LEFT JOIN Table2 AS p2 ON Table1.worker2 = Table2.ID
WHERE ...
$table = mysql_query(...);
$rec = mysql_fetch_assoc($table);
$worker1name = $rec['???'];
$worker2name = $rec['???'];
What do I insert in those last two statements to get the two names. Or more precisely what do I have to add to the SELECT to specify what I want the two different versions of the NAME field from table 2 to be called please?
You should alias the fields also like this:
SELECT
xxx,
p1.NAME as p1name,
p2.NAME as p2name
FROM Table1
LEFT JOIN Table2 AS p1 ON Table1.worker1 = p1.ID
LEFT JOIN Table2 AS p2 ON Table1.worker2 = p2.ID
WHERE ...

PHP SQL Request - Query 2 tables, for results on one query

I need to query the database to pull all cars that a particular user likes.
I know that user_id is 1
Then I have 2 tables. 1 contains all the cars ... id and description and table 2 contains the likes.
Table 1 has a list if cars and these fields:
car_id
car_name,
car_description
Table 2 has what cars I like and these fields:
user_id
car_id
likes (1 or 0)
So I need to pull out only the records that user 1 likes from Table 2 but only the ones he likes
What SQL query would I need to do for that?
SELECT * FROM table1 as t0
LEFT JOIN table2 as t1 on t0.car_id = t1.car_id
WHERE t1.likes = 1
Try this
SELECT * FROM table1 as t1 LEFT JOIN table2 as t2 on t1.car_id = t2.car_id WHERE t2.user_id = $user_id
Try this query
SELECT t1.*,t2.*
FROM tbl1 t1,tbl2 t2
WHERE likes = 1 AND user_id = 1 AND t1.car_id = t2.car_id

Pull MIN and MAX prices from database

I need to select all (*) the rows from table1, table2, table3.. but I need to select the MIN and MAX price from table 2 within this INNER JOIN. I've read up on how to do this, but how do I do this within an INNER JOIN, and how do I display it in a PHP variable.
Initial Problem: How do I display the min and max values once I pull them.. (e.g $Result['MinPrice'], $Result['MaxPrice']).
Here's my query:
$Query = mysql_query("
SELECT *
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table2.DeviceID = table3.DeviceID
WHERE table2.DeviceID = '$GetDeviceID'
");
Here is the tables structure:
table1 = usersinfo
UserID UserFirstName UserLastName UserDisplayName
1 John Doe John D.
table2 = listings
ListingID UserID DeviceID
11 1 2
table3 = devices
DeviceID
2
If you really want to do what you're asking in this way you can use the query that is displayed below. This does, however, return a lot of duplicate rows if you have multiple rows returned when querying. Try it and see if it works.
$Query = mysql_query("
SELECT table1.*, table2.*, table3.*,
MIN(table2.price) as minny,
MAX(table2.price) as maxxy
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table1.DeviceID = table3.DeviceID
WHERE table1.DeviceID = '$Something'
GROUP BY table2.ListingAskingPrice
");
Then get this value by doing $result['minny'] and $result['maxxy']

Categories