MySQL get Parent as Heading and children as items - php

Hello I have a database structure like this and some data in it
id | parent_id | name
1 | 0 | Nissan
2 | 1 | 240SX
3 | 1 | 350z
4 | 0 | Toyota
5 | 4 | Camry
6 | 4 | Prado
7 | 1 | Skyline
8 | 4 | Hilux
I want to take Nissan as heading and after show all the models. As well Toyota as heading and it's models below it. How do I achieve this using one query? Is it even possible?

You should normalize your database or at least separate your columns so there is a manufacturer column and a model column. This will then help you do a query such as
SELECT * FROM CARS WHERE manufacturer = 'Toyota';
or
SELECT * FROM CARS GROUP BY manufacturer;
But the best practise would be to have a table for storing manufacturers and a table for storing all models of the cars, then a table for storing your cars itself which will have 2 columns that are referenced from the other 2 tables.
So this will become:
id | parent_id | manufacturer_id | model_id
1 | 0 | 1 | 2 |
2 | 1 | 4 | 1 |
3 | 1 | 3 | 6 |
4 | 0 | 3 | 9 |
you will then do a query to join the 3 tables
SELECT cars.id, cars.parent_id, cars.manufacturer_id, cars.model_id, t1.manufacturer_name, t2.model_name from CARS
JOIN manufacturer_table t1
ON t1.manufacturer_id = cars.manufacturer_id
JOIN model_table t2
ON t2.model_id = cars.model_id
hope that helps

Try this, it should solve your problem:
SELECT
child.*
FROM
{your_table} parent
LEFT JOIN
{your_table} child ON child.parent_id = parent.id
OR (child.parent_id = 0 AND child.id = parent.id)
WHERE
parent.parent_id = 0
ORDER BY
parent.id, child.parent_id, child.name
{your_table} should be replaced in two places with your table's name (which you presented in the question).

Related

Finding inner join mysql with array [duplicate]

This question already has answers here:
How to join two tables using a comma-separated-list in the join field
(5 answers)
Closed 2 years ago.
I have two tables, First one is products where it has list of products with some specifications, in the other hand I have a table with clients and what type of product they want, they might want a product in any town of a list exactly as explained in the following tables,
Products Table like
| id | owner | userid | city | town | status | price |
| 1 | jon spee | 10 | 10 | 4 | 0 | 10500 |
| 2 | Hiss Roe | 10 | 7 | 9 | 0 | 20000 |
| 3 | John Smi | 10 | 10 | 12 | 0 | 10000 |
Clients Table like
| id | fullname | userid | city | towns | status | price |
| 1 | name 1 | 10 | 10 |4,8,6,2| 0 | 20000 |
| 2 | name 2 | 10 | 7 | 7,2,9 | 0 | 25000 |
| 3 | name 3 | 10 | 10 | 1 | 0 | 20000 |
MySQL Query :
SELECT *
FROM clients
INNER JOIN products
ON (
clients.userid = products.userid AND
clients.price >= products.price AND
clients.city = products.city AND
clients.status = products.status
I want it to check also in towns like for each town it executs this query (dynamically),
(products.town LIKE '%4%' OR products.town LIKE '%8%' OR products.town LIKE '%6%' OR products.town LIKE '%2%')
You could go with this query
SELECT *
FROM clients
INNER JOIN products
ON (
clients.userid = products.userid AND
clients.price >= products.price AND
clients.city = products.city AND
find_in_set(clients.town, products.town) AND
clients.status = products.status
you can also fetch it in php and create your statement based on the results fetched
Your primary effort should go into fixing your data model. Don't store multiple integer values in a string column. You should have a separate table to store the relation betwen clients and towns, which each tuple on a separate row.
That said: for your current design, you can join on find_in_set():
on
clients.userid = products.userid
and ...
and find_in_set(product.town, client.towns)

Relation among three tables: proper query and design suggestion

I have three tables (MySQL):
families where I define the products' families
products where I define the products
families_products where I relate families and products
------------------- -------------------- ------------------------
| familyID | code | | productID | code | | familyID | productID |
|----------|------| |-----------|------| |----------|-----------|
| 1 | p | | 1 | p3 | | 1 | 1 |
| 2 | a | | 2 | a5 | | 1 | 3 |
| 3 | e | | 3 | p1 | | 1 | 6 |
------------------- | 4 | e7 | | 2 | 2 |
| 5 | a2 | | 2 | 5 |
| 6 | p4 | | 3 | 4 |
-------------------- ------------------------
I have two questions:
Is this design convenient or is it better drop the families_products table putting the familyID relation directly into the table products?
With a design like this one, if I have the familyID how can I retrieve the products->code? I wrote this query but a query structure like this one would work if I drop the families_products table putting the familyID relation directly into the table products as said before, not in the case of a third relational table.
'SELECT productID, code, img
FROM products AS a
INNER JOIN families_products AS b
ON b.productID=a.productID
WHERE b.familyID=' . $families[$key]["familyID"]
Your data structure is fine.
If you have at most one familyID per product, then you should put the family in the products table. You should use the junction table (your structure) if a product can be part of multiple families.
As for your query, it is fine. I would use better table aliases:
SELECT p.productID, p.code, ??.img
FROM products p INNER JOIN
families_products fp
ON f.productID = fp.productID
WHERE fp.familyID = ' . $families[$key]["familyID"]
If your product only belongs to one product family you can skip the "familiy_product" table and add the familiy_id directly to the product. Only in case a product can be assigned to multipl families you need the "join" table.
With only two tables the SQL is quite easy:
select p.code from family f, product p where f.code ='xx' and p.family_id = f.id

How to select values from two different tables in SQL

I have two tables in my SQL Server database. The first is catgeories and second is products. There is a column categories_id in both tables.
HERE IS MY TABLE FOR CATEGORIES :
+----+----------+----------+
| id | category | parent |
+----+----------+----------+
| 1 | BOY | 0 |
| 2 | GIRL | 0 |
| 3 | SHIRT | 1 |
| 4 | SKIRT | 2 |
| 5 | JACKET | 1 |
+----+----------+----------+
TABLE : PRODUCTS
+-------+--------------+----------------------+
| id | title |PRICE | Categories |
+-------+--------------+------+---------------+
| 1 | RED SHIRT | 300 | 3 |
| 2 | blue SKIRT | 500 | 4 |
| 3 | jeans jacket | 500 | 3 |
+-------+--------------+------+-----+---------+
Now I want to select the values from Products table for a particular category like BOY.
Try This:
SELECT pr.id,pr.title,pr.price from products AS pr
INNER JOIN CATEGORIES AS cat ON cat.id=pr.Categories
WHERE cat.category='Boy';
SELECT products.* FROM products INNER JOIN categories ON products.categories = categories.id WHERE categories.category LIKE '%BOY%';
Use this query..
Either
SELECT * FROM tproducts WHERE categories = 1
or
SELECT * FROM tproducts
JOIN tcategories ON tcategories.id = tproducts.categories WHERE tcategories.category = 'BOY'
I don't know your table names so I just used tproducts and tcategories
There is no boy(1) ID in Categories(field) in PRODUCTS(table)
SELECT * FROM CATEGORIES
INNER JOIN PRODUCTS
ON CATEGORIES.id=PRODUCTS.Categories
WHERE CATEGORIES.category ='BOY'
FOR this use join query Example:
select *(or you can get any column as you write name) from table1 join table2 on table1.id=table2.id where table1.category='BOY';

How to get COUNT and INNER JOIN related with concated value field in mysql

I have 2 tables
table A
tag_id | Tag_name
1 | tg1
2 | tg2
3 | tg3
4 | tg4
table B
id | name |tag_id
1 | avq | 1,2,4
2 | bdq | 2
3 | abc | 3,2
4 | vdf | 1,4
5 | zxc | 3
I want to inner join both tables and get its count using tag_id in the following format
`tg1=> 2,tg2=> 3,tg3=> 2,tg4=> 2`
How is it possible in a single MySQL query?
The best option is to normalize the 2nd table and create an association table for storing the tag id and the id of the 2nd table. In the meanwhile the following should do the job but for long run you need to normalize the table else more problems will happen in future
select
t1.Tag_name, count(*) as total
from tableA t1
join tableB t2 on find_in_set(t1.tag_id,t2.tag_id) > 0
group by t1.tag_id ;
You need to create relation table. For example:
Tag table:
+----+----------+
| id | name |
+----+----------+
| 1 | Tag name |
+----+----------+
| 2 | Tag 2 |
+----+----------+
B Table:
+----+-----------+
| id | title |
+----+-----------+
| 1 | Any title |
+----+-----------+
Reference table ex. :
+------+--------+
| b_id | tag_id |
+------+--------+
| 1 | 1 |
+------+--------+
| 1 | 2 |
+------+--------+
In your reference table you put many tags for one B element. In this example you see two tags assigned by reference to b_id = 1
select tag_name, count(position)
from (
select a.tag_name, FIND_IN_SET(a.tag_id,b.tag_id) as position
from a,b
) as tmpTB
where position !=0
group by tag_name

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.

Categories