join query in same table with condition - mysql

I have inserted both category and sub-category in same table.
id , name , mainCat ,
Here is the name of the category .If a user add a subcategory then i will add the parent category to maincat and sub category to the name.
but when come sorting i have sort Category wise.
can any one suggest me best query

As long as you only have two levels of categories then a query like the following using a self-join will suffice. However, if you have many levels (i.e. a hierarchy) then the problem becomes a lot harder. See http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ for more information.
SELECT p.Name, s.Name
FROM Categories s
LEFT JOIN Categories p ON s.mainCat = p.ID
ORDER BY p.Name, s.Name;

i tried with query a lot but finally i made it with php
$category = mysql_query("SELECT * FROM category WHERE mainCat = '' ORDER BY `name` ASC");
while($data = mysql_fetch_array($category)){
$array[] = $data;
$subCategory = mysql_query("SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC");
echo "SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC".'<br/>';
while($data2 = mysql_fetch_array($subCategory)){
if($data2['mainCat']!=""){
$array[] = $data2;
}
}
}

have u try below:
SELECT t1.id, t1.name
FROM tablename t1
LEFT JOIN tableName t2
ON t2.name = t1.mainCat

Related

MySQL query using DISTINCT return one from many possible options

It was hard to come up with a good title for this one. I have a query selecting products from my table. Each product may belong to multiple categories. So when I add in the 'category' to my DISTINCT query, it sometimes returns multiple of the same product because that product belongs to more than one category. I want my query to just pick one of the categories and return that, doesn't matter which one.
Here is my query:
SELECT DISTINCT ci.NAME,
ci.pid,
ci.description,
ci.price,
ci.saleprice,
ci.ingredients,
ci.allergens AS allergens,
ci.isfood,
ci.quantity,
ci.ismostpopular,
ci.activedate,
ci.isfrozen,
cc.NAME AS category
FROM cart_category cc
JOIN cart_item_category cic
ON cc.id = cic.catid
JOIN cart_item ci
ON cic.itemref = ci.itemref
WHERE cc.active = 1
AND ci.active = 1
AND ci.isdeleted = 0
AND ci.isfrozen = 0
AND ( ci.NAME LIKE '%dark%'
OR ci.pid = '%dark%' )
AND ci.quantity > 5
AND cc.NAME <> "nutritionals";
When I add in cc.name as category is when it returns multiple of the same product.
try just to limit it:
... LIMIT 1

MySQL combine UPDATE and SELECT query

I have the following SELECT statement that returns data, example below:
SELECT performers.ID,
performers.Name,
COUNT(*) AS CountOfDeals,
COUNT(DISTINCT(deals.Name)) AS CountOfAliases
FROM deals RIGHT JOIN performers
ON deals.name LIKE CONCAT('%', performers.name, '%')
WHERE performers.ID IN ( 27952, 27951, 27950, 27949, 27948 )
GROUP BY Name;
Example data returned:
ID Name CountOfDeals CountOfAliases
27952 Christine Hoberg 1 0
27951 Indian Jewelry 1 0
27952 Kinky Friedman 5 3
27949 KJ-52 1 0
27960 River Whyless 1 0
I want to combine this with the following UPDATE statement
UPDATE performers
SET RawAliasCount = CountOfAliases,
RawDealCount = CountOfDeals
WHERE ID = ?
All the values needed to run the update statement are returned in the select statement above so hopefully this should be pretty easy.
Thanks.
Use update with join:
UPDATE performers p JOIN
(SELECT performers.ID, performers.Name, COUNT(*) AS CountOfDeals,
COUNT(DISTINCT(deals.Name)) AS CountOfAliases
FROM deals RIGHT JOIN
performers
on deals.name LIKE CONCAT('%', performers.name, '%')
WHERE performers.ID IN (27952, 27951, 27950, 27949, 27948)
GROUP BY Name
) pp
ON pp.id = p.id
SET RawAliasCount = pp.CountOfAliases,
RawDealCount = pp.CountOfDeals;
UPDATE performers
SET performers.RawAliasCount = count_table.CountOfAliases, performers.RawDealCount = count_table.CountOfDeals
FROM performers
INNER JOIN
(
SELECT
performers.ID, performers.Name, COUNT(*) AS CountOfDeals,
COUNT(DISTINCT(deals.Name)) AS CountOfAliases
FROM deals RIGHT JOIN performers on deals.name LIKE CONCAT('%', performers.name, '%')
WHERE performers.ID IN (27952, 27951, 27950, 27949, 27948)
GROUP BY Name
) count_table
ON count_table.ID = performers.ID;
When this type of question is asked, thank you to put the tables schema.
edit : sorry, it's sql-server syntax.

SQL Join on user entered Title

I have a Blog and BlogCategories. A user can enter a category title, which will then pull all Blogs that have the category associated with it.
My set up is:
Blog:
ID
BlogCategoryID
BlogCategory:
ID
Title
My most recent attempt:
$sqlQuery = new SQLQuery();
$sqlQuery->select = array (
'*',
);
$sqlQuery->from = array (
"BlogEntry",
"LEFT JOIN BlogCategory ON BlogCategory.ID = '$category'"
);
$result = $sqlQuery->execute();
How do I achieve this?
Many thanks for your time.
You can use an INNER JOIN query as follow
SELECT *
FROM Blog a
INNER JOIN BlogCategory b
ON a.BlogCategoryID = b.ID
WHERE b.Title LIKE 'title_here'

How can I count products in category

I have a table with categories in nested set model, I would like to take the categories with how many products they have. something like this
Categories-(6)
Cars-(4)
BMW-(2)
Opel-(1)
Mercedes-(1)
Trucks-(2)
Man-(1)
Mercedes-(1)
I have two tables, categories and types
Categories:id,name,level,lft,rgt
Types:id,category_id,name
Now I'm able to list only the categories with this:
$categories = Doctrine_Core::getTable('Category')
->createQuery('c1')
->select('c1.id, c1.level, c1.name')
->innerJoin('c1.Category c2 ON ( c1.lft BETWEEN c2.lft AND c2.rgt )')
->andWhere(' c2.id = ?', $id)
->andWhere('c1.level > 0')
->andWhere('c1.level < c2.level+3')
->groupBy('c1.id')
->orderBy('c1.lft')
->execute();
Is there anyway to return the count like that one above?
select table1.name,table2.countcars
from categories as table1 right join
(select category_id,count(*) as countcars
from cars group by category_id) as table2
on table1.id=table2.category_id;
You'll get
BMW-(2)
Opel-(1)
Mercedes-(1)
from above query
for Cars-(4)
you'll simply have to do this
select count(*) as numberOfCars from cars;

combing two SELECT statements into a JOIN

I have two tables: table_1: item_id, name ... table_2: image_id, item_id, url
The following function retrieves the 'urls' of the items with the '$name' that is passed in. I first need to get the 'item_id' from table_1 to use in the query. I only need to return the 'url's from table_2.
It currently works fine, but I feel it could be streamlined to be done in one query with a JOIN rather than two separate queries. I've tried using different 'JOIN's to make it work but I can't seem to get it right.
Here's the function as it stands now with the two queries...
function get_items( $name ) {
global $wpdb;
$sql1 = "SELECT `item_id` FROM `table_1` WHERE `name` = '$name'";
$results1 = $wpdb->get_var( $sql1 );
$sql1 = "SELECT `url` FROM `table_2` WHERE `item_id` = '$results1'";
$results2 = $wpdb->get_results( $sql1, ARRAY_A );
return $results2;
}
and here is the 'JOIN' that I tried implementing, but was unsuccessful (I've also switched it around and did a 'LEFT/RIGHT JOIN' as well resulting in the same result) ...
$sql1 = "SELECT `table_2`.`url`
FROM `table_2`
INNER JOIN `table_1`
ON `table_2`.`item_id` = `table_1`.`item_id`
WHERE `table_1`.`item_id` = '$name'";
Any advice on combining these two queries?
The problem with your query is this WHERE table_1.item_id = '$name', it should be the name not the item_id
SELECT b.url
FROM table1 a
INNER JOIN table2 b
ON a.item_id = b.item_id
WHERE a.name = '$name'
select url from table_2 where item_id IN (select item_id from table_1 where name = $name )