Query to select from multiple tables - php

I know that there are several posts about this, but I can't get this to work. I don't have any experience of MySQL "join" or "left", only simple querys.
I've got 3 tables: categories, companies and catcomp
Categories
id | name | ... | ... |
1 | Foo
2 | Bar
Companies
id | name | ... | ...
1 | Company1
2 | Company2
Catcomp (To store multiple categories for one company)
company_id | category_id
1 | 1
1 | 2
2 | 2
I've only got this:
$result = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($result))
{
echo '<input type="checkbox" id="'.$row['id'].'" name="cat[]" value="'.$row['id'].'">'.$row['name'].'<br>
}
This prints out all categories with check boxes.. I want the boxes to be checked for the current company.
Any ideas?

There's probably more elegant solutions but anyway...
DROP TABLE IF EXISTS categories;
CREATE TABLE categories
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL UNIQUE
);
INSERT INTO categories VALUES
(1 ,'Foo'),(2,'Bar'),(3,'Boo');
DROP TABLE IF EXISTS companies;
CREATE TABLE companies
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL UNIQUE
);
INSERT INTO companies VALUES
(1,'Company1'),(2,'Company2'),(3,'Company3');;
DROP TABLE IF EXISTS company_category;
CREATE TABLE company_category
(company_id INT NOT NULL,category_id INT NOT NULL,PRIMARY KEY(company_id,category_id));
INSERT INTO company_category VALUES (1 ,1),(1 ,2),(2 ,2);
SELECT o.id company_id
, o.name company_name
, a.id category_id
, a.name cateory_name
, CASE WHEN oa.company_id IS NOT NULL THEN ' checked' ELSE '' END checked
FROM companies o
JOIN categories a
LEFT
JOIN company_category oa
ON oa.company_id = o.id
AND oa.category_id = a.id;
+------------+--------------+-------------+--------------+----------+
| company_id | company_name | category_id | cateory_name | checked |
+------------+--------------+-------------+--------------+----------+
| 1 | Company1 | 1 | Foo | checked |
| 2 | Company2 | 1 | Foo | |
| 3 | Company3 | 1 | Foo | |
| 1 | Company1 | 2 | Bar | checked |
| 2 | Company2 | 2 | Bar | checked |
| 3 | Company3 | 2 | Bar | |
| 1 | Company1 | 3 | Boo | |
| 2 | Company2 | 3 | Boo | |
| 3 | Company3 | 3 | Boo | |
+------------+--------------+-------------+--------------+----------+
http://www.sqlfiddle.com/#!2/11e6e/1

Select c.category_id,c.name as categoriesname,b.name as companyname from catcomp a ,companies b, categories c
where a.company_id = b.id and a.category_id = c.id
use this query

Usin example from Strawberry
SELECT categories.name as catename, companies.name as compname from company_category
INNER JOIN companies on (companies.id=company_category.company_id)
INNER JOIN categories on (categories.id=company_category.category_id)
where company_category.category_id = categories.id and categories.id=1
I want the boxes to be checked for the current company.
You need in company_category table any status or column with check status, and the query stay:
SELECT categories.name as catename, companies.name as compname from company_category
INNER JOIN companies on (companies.id=company_category.company_id)
INNER JOIN categories on (categories.id=company_category.category_id)
where company_category.category_id = categories.id and company_category.status=1
where 'status' is company has been checked or not...

Edit the below query with your table details . I Tried it and its working .
SELECT definition.definition,relation.rtype,word.word FROM definition INNER JOIN relation
ON definition.id = relation.id INNER JOIN word ON definition.id = word.id

Related

MySQL : LEFT JOIN for 4 tables which are connected to each other

I have 4 tables as below:
1) courses
| ID - > Primary Key | Name
-------------------------------
| 1 | Course 1
| 2 | Course 2
| 3 | Course 3
2) countries
| IDPrimary Key | Name
-------------------------------
| 1 | Country 1
| 2 | Country 2
| 3 | Course 3
3) universities
| ID - > Primary Key | Name | country_id
---------------------------------------------------
| 1 | University 1 | 1
| 2 | University 2 | 1
| 3 | University 3 | 3
4) university_courses
| ID - > Primary Key | university_id | course_id
----------------------------------------------
| 1 | 1 | 2
| 2 | 3 | 2
| 3 | 3 | 3
Now, I need to create one REST API in core PHP for android app in that I will get two parameters country_id and course_id. Both will contain multiple values like country_id = "3,4,5" and course_id = "1,6,8".
I have to response all the related universities according to the country and course.
I have tried below query but i am not getting desired output so please help me if anyone have idea for my problem.
SELECT * FROM universities LEFT JOIN countries ON countries.id = universities.country_id LEFT JOIN university_courses ON universiity_courses.university_id = universities.id LEFT JOIN courses ON courses.id = university_courses.course_id WHERE FIND_IN_SET(universities.country_id, ?) AND FIND_IN_SET(university_courses.course_id, ?)
If course_id = 1,2 and country_id = 2,3, my desired output should be:
| university_id |
| 3 |
UPDATE:
Above issue is solved but now facing new issue is getting same university multiple time in result like:
if course_id = 2,3 I am getting response as:
|university_id |
------------------
|3 |
|3 |
For that I have used GROUP BY clause but getting 500 Internal Server Error if I remove GROUP BY It will work fine What can be the issue?
My new query is as below:
SELECT * FROM universities LEFT JOIN university_courses ON university_courses.university_id = universities.id LEFT JOIN courses ON courses.id = university_courses.course_id LEFT JOIN countries ON countries.id = universities.country_id WHERE FIND_IN_SET(university_courses.course_id, ?) AND FIND_IN_SET(universities.country_id, ?) GROUP BY university_courses.university_id
use LEFT OUTER JOIN not LEFT JOIN
SELECT * FROM universities LEFT OUTER JOIN countries ON countries.id = universities.country_id LEFT OUTER JOIN university_courses ON universiity_courses.university_id = universities.id LEFT OUTER JOIN courses ON courses.id = university_courses.course_id WHERE FIND_IN_SET(universities.country_id, ?) AND FIND_IN_SET(university_courses.course_id, ?)

mysql select where left join syntax

I have a problem. I have 2 database tables.
table 1 people:
+----------+--------------+
| id | name |
+----------+--------------+
| 1 | johanalj |
| 2 | hjgjhggjh |
+----------+--------------+
table 2 images of people:
+----------+--------------+----------------+
| id | url | people_ID |
+----------+--------------+----------------+
| 1 | 3765345.png | 1 |
| 2 | 87e58974.png | 1 |
+----------+--------------+----------------+
Now I want to select person with id 1 from table 1 and all pictures from table 2 that have people_ID 1.
I tried LEFT JOIN in combination with a WHERE but cant get it to work
$sql = "SELECT * FROM people p LEFT JOIN images i ON i.people_ID = p.id WHERE id = '1'";
But I get a no result massage. What am I doing wrong?
There is an error(ambiguous column id). Both tables have id column. You need to add the table alias with id. try with -
$sql = "SELECT * FROM people p LEFT JOIN images i ON i.people_ID = p.id WHERE p.id = '1'";

PHP MySQL joining two tables with conditional joins

So, I have a database that I am creating. It stores information about families and each family member. It then uses those records to associate invoices to either a family or family member.
My dilemma is that I need to list all of these invoices to a page under the families record i.e. create a list of invoices associated to either the family itself or an individual family member.
Table Structure
invoices
id | date_entered | invoice_date | invoice_number | invoice_amount | client_type | unique_id | supplier_type | supplier_id | category_id | childcare_hours
---+--------------+--------------+----------------+----------------+-------------+-----------+---------------+-------------+-------------+----------------
1 | 1411098397 | 1411048800 | 123 | 0.01 | 0 | 137 | 0 | 139 | 5 | NULL
families
id | ufi | last_name | address_1 | address_2 | city_id | phone | mobile | email | f_d_worker_1 | f_d_worker_2 | status_id | trans_date | entry_date | exit_date | eligible_date | active_date | lga_loc_id | facs_loc_id | ind_status_id | referral_id | active_status | comm_org_id | notes
---+----------+-----------------+-------------+-----------+---------+-------+--------+-------+--------------+--------------+-----------+------------+------------+-----------+---------------+-------------+------------+-------------+---------------+-------------+---------------+-------------+-------
1 | 1-XEWUDZ | Forsyth - Ennis | Skinner St. | NULL | NULL | NULL | NULL | NULL | 13 | NULL | 1 | NULL | 1341324000 | NULL | 1341842400 | 1342620000 | 7 | 1 | 3 | NULL | 1 | 1 | NULL
clients (family members)
id | upi | last_name | first_name | birthdate | sex | phone | mobile | email | indig_status_id | referral_id | relationship_id | preschool_id | family_id | notes
---+----------+-----------+------------+------------+-----+-------+--------+-------+-----------------+-------------+-----------------+--------------+-----------+------
1 | 1-XFCBBP | Ennis | Jason | 20/09/1996 | 1 | NULL | NULL | NULL | 3 | NULL | NULL | NULL | 1 | NULL
My current SQL looks like:
SELECT `invoices`.`id`, `invoices`.`date_entered`, `invoices`.`invoice_date`, `invoices`.`invoice_number`, `invoices`.`invoice_amount`, `invoices`.`client_type`, `invoices`.`unique_id`, `unique1`.`ufi`, `unique2`.`upi`, `unique1`.`last_name`, `invoices`.`supplier_type`, `invoices`.`supplier_id`, `suppliers`.`name`, `invoices`.`category_id`, `cat1`.`name`, `cat2`.`name`, `invoices`.`childcare_hours`
FROM `invoices`
LEFT OUTER JOIN `suppliers` ON `suppliers`.`id` = `invoices`.`supplier_id`
LEFT OUTER JOIN `categories` cat1 ON `cat1`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `preschool_types` cat2 ON `cat2`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `families` unique1 ON `unique1`.`id` = `invoices`.`unique_id`
LEFT OUTER JOIN `clients` unique2 ON `unique2`.`id` = `invoices`.`unique_id`
WHERE (`invoices`.`unique_id` = ? AND `unique1`.`ufi` = ?) LIMIT 0, 10
But what I need a query that checks the client_type column and if it equals 1 it needs to look in the clients table BUT it needs to look for members of the same family, identified by the id row in the families table
SOLUTION
Ok, so after much, much (much) screwing around and a little research. It appears that #cupid was correct (Although very brief in his answer).
And I will explain the solution better (in hope that this will help someone later).
The UNION option in MySQL (and most likely other SQL) allows you to combine the result sets of two (or more) SELECT queries, into one result set. This is extremely helpful if you have similar data, in separate tables that you may want to select easily and process as one request. Also helpful (in my case) for pagination, by allowing you to utilise SQL's LIMIT option.
One thing to take into consideration is that, the UNION syntax uses the columns from the first SELECT statement as the column names for all following queries, also you need to make sure that you have the same amount of columns selected in all queries for this to work.
(
SELECT
`invoices`.`id`,
`invoices`.`date_entered`,
`invoices`.`invoice_date`,
`invoices`.`invoice_number`,
`invoices`.`invoice_amount`,
`invoices`.`client_type`,
`invoices`.`unique_id`,
`clients`.`upi`,
`clients`.`last_name`,
`clients`.`family_id`,
`invoices`.`supplier_type`,
`invoices`.`supplier_id`,
`suppliers`.`name`,
`invoices`.`category_id`,
`cat1`.`name`,
`cat2`.`name`,
`invoices`.`childcare_hours`
FROM
(
`invoices`
LEFT OUTER JOIN `suppliers` ON `suppliers`.`id` = `invoices`.`supplier_id`
LEFT OUTER JOIN `categories` cat1 ON `cat1`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `preschool_types` cat2 ON `cat2`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `clients` ON `clients`.`id` = `invoices`.`unique_id`)
WHERE
`clients`.`family_id` = 47 AND `invoices`.`client_type` = 1
)
UNION
(
SELECT
`invoices`.`id`,
`invoices`.`date_entered`,
`invoices`.`invoice_date`,
`invoices`.`invoice_number`,
`invoices`.`invoice_amount`,
`invoices`.`client_type`,
`invoices`.`unique_id`,
`families`.`ufi`,
`families`.`last_name`,
`families`.`id`,
`invoices`.`supplier_type`,
`invoices`.`supplier_id`,
`suppliers`.`name`,
`invoices`.`category_id`,
`cat1`.`name`,
`cat2`.`name`,
`invoices`.`childcare_hours`
FROM `invoices`
LEFT OUTER JOIN `suppliers` ON `suppliers`.`id` = `invoices`.`supplier_id`
LEFT OUTER JOIN `categories` cat1 ON `cat1`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `preschool_types` cat2 ON `cat2`.`id` = `invoices`.`category_id`
LEFT OUTER JOIN `families` ON `families`.`id` = `invoices`.`unique_id`
WHERE
`invoices`.`unique_id` = 47 AND `invoices`.`client_type` = 0
)
Have you thought about using UNION?

MySQL struggling with a query to find similar details among products

I have a query to write and I am absolutely stumped on how to do it. Here's my situation, I am trying to provide a particular product_ID, then match all of the other product_IDs in the database that have at least the same intDescription_detail_IDs as the provided product_ID.
The relevant tables look like this:
tblproducts
=========================
product_ID | product_name
=========================
| 1 | dresser |
| 2 | bookcase |
| 3 | table |
| 4 | chair |
=========================
tbldescriptions
=========================================================================
|description_ID| intDescription_product_ID | intDescription_detail_ID |
=========================================================================
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 6 |
| 7 | 3 | 1 |
| 8 | 3 | 3 |
| 9 | 3 | 4 |
| 10 | 4 | 1 |
| 11 | 4 | 2 |
| 12 | 4 | 7 |
As an example, if I provided the product_ID "1", then I would like to return all of the product_IDs that at least have intDescription_detail_ID 1 and 2.
So, the product_IDs that should be returned are 1, 2, and 4, because all of these products have the intDescription_detail_ID of 1 and 2 among their details.
I am highly confused about how to write a query like this, so any help is greatly appreciated!
I should warn you by saying that I may have made a silly mistake here...
DROP TABLE IF EXISTS products;
CREATE TABLE products(product_ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,product_name VARCHAR(20) NOT NULL UNIQUE);
INSERT INTO products VALUES
(1,'dresser'),
(2,'bookcase'),
(3,'table'),
(4,'chair');
DROP TABLE IF EXISTS product_detail;
CREATE TABLE product_detail
(product_id INT NOT NULL
,detail_id INT NOT NULL
,PRIMARY KEY(product_id,detail_id)
);
INSERT INTO product_detail VALUES
(1,1),
(1,2),
(2,1),
(2,2),
(2,6),
(3,1),
(3,3),
(3,4),
(4,1),
(4,2),
(4,7);
SELECT DISTINCT c.product_id
FROM product_detail a
JOIN product_detail b
ON b.product_id = a.product_id
AND b.detail_id <> a.detail_id
JOIN product_detail c
ON c.product_id <> a.product_id
AND c.detail_id = a.detail_id
JOIN product_detail d
ON d.product_id = c.product_id
AND d.detail_id = b.detail_id
WHERE a.product_id = 1;
+------------+
| product_id |
+------------+
| 2 |
| 4 |
+------------+
Alternative to #Strawberry’s suggestion with JOINs this can also be done using HAVING for filtering products that have (at least) the same number of rows with the same intDescription_detail_IDs as the product the search is done for:
SELECT intDescription_product_ID
FROM tbldescriptions t1
WHERE intDescription_detail_ID IN (
SELECT intDescription_detail_ID
FROM tbldescriptions t2
WHERE t2.intDescription_product_ID = 1
)
GROUP BY intDescription_product_ID
HAVING count(*) >= (
SELECT count(intDescription_detail_ID)
FROM tbldescriptions t3
WHERE t3.intDescription_product_ID = 1
)
http://sqlfiddle.com/#!2/ce698/2
One should keep in mind though that HAVING is applied last, so that will select all products with at least one matching intDescription_detail_ID first, and filter the results based on the actual count afterwards – so depending on the size and characteristic of your data set that might not be the best performing solution.

How to SELECT records from One table If Matching Record In Not Found In Other Table

Halo i am trying for a query to select record from one table say 'deal_asking' only if a matching record is not found in the second table 'deal_unpluged'. this what i does (below) selecting record using LEFT JOIN and then filter the record in PHP side.
What i am looking for an Mysql query way of solution for this problem please help..
thanks in advance...
SELECT DA.das_id, DU.das_id_fk
FROM deal_asking DA
LEFT JOIN deal_unpluged DU ON DA.das_id= DU.das_id_fk
WHERE department='8'
ORDER BY das_id ASC LIMIT 10 OFFSET 0
Just add this to your WHERE clause:
AND DU.das_id_fk IS NULL
Say I have the following two tables:
+-------------------------+ +-------------------------+
| Person | | Pet |
+----------+--------------+ +-------------------------+
| PersonID | INT(11) | | PetID | INT(11) |
| Name | VARCHAR(255) | | PersonID | INT(11) |
+----------+--------------+ | Name | VARCHAR(255) |
+----------+--------------+
And my tables contain the following data:
+------------------------+ +---------------------------+
| Person | | Pet |
+----------+-------------+ +-------+----------+--------+
| PersonID | Name | | PetID | PersonID | Name |
+----------+-------------+ +-------+----------+--------+
| 1 | Sean | | 5 | 1 | Lucy |
| 2 | Javier | | 6 | 1 | Cooper |
| 3 | tradebel123 | | 7 | 2 | Fluffy |
+----------+-------------+ +-------+----------+--------+
Now, if I want a list of all Persons:
SELECT pr.PersonID, pr.Name
FROM
Person pr
If I want a list of Persons that have pets (including their pet's names):
SELECT pr.PersonID, pr.Name, pt.Name AS PetName
FROM
Person pr
INNER JOIN Pet pt ON pr.PersonID = pt.PersonID
If I want a list of Persons that have no pets:
SELECT pr.PersonID, pr.`Name`
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
WHERE
pt.`PetID` IS NULL
If I want a list of all Persons and their pets (even if they don't have pets):
SELECT
pr.PersonID,
pr.Name,
COALESCE(pt.Name, '<No Pet>') AS PetName
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
If I want a list of Persons and a count of how many pets they have:
SELECT pr.PersonID, pr.Name, COUNT(pt.PetID) AS NumPets
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
GROUP BY
pr.PersonID, pr.Name
Same as above, but don't show Persons with 0 pets:
SELECT pr.PersonID, pr.Name, COUNT(pt.PetID) AS NumPets
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
GROUP BY
pr.PersonID, pr.Name
HAVING COUNT(pt.PetID) > 0

Categories