How to get only matching records using LIKE Statement - mysql

How to get the matching records from both the tables
Matching Table
CREATE TABLE matching (
ID INT,
Name varchar(20)
);
INSERT INTO matching(ID,name) VALUES (1,'Child'),(2,'GrandChild'),(3,'parent')
TreeMatching
CREATE TABLE Treematching (
ID INT,
Name varchar(20)
);
INSERT INTO Treematching(ID,name) VALUES
(1,'Child-Foster'),
(2,'Child-Filly'),
(3,'Child-Ricky'),
(4,'GRandchild-Filmy'),
(5,'GRandchild-Freaky'),
(6,'GRandchild-Frim'),
(7,'Frim'),
(8,'None'),
(9,'parent-John')
How to get the matching records from Tree matching tables
output :
ID Name TName
1 Child Child-Foster
2 Child Child-Filly
3 Child Child-Ricky
4 GRandchild GRandchild-Filmy
5 GRandchild GRandchild-Freaky
6 GRandchild GRandchild-Frim
9 parent parent-John
How to get the same records using like statements I have tried using CONCAT .

You could try something like this, if you use SQL Server:
SELECT
t.ID,
m.Name,
t.Name
FROM matching AS m
INNER JOIN Treematching AS t
ON t.Name LIKE '%'+m.Name+'%'
While you try this if you use MySQL Server:
SELECT
t.ID,
m.Name,
t.Name
FROM matching AS m
INNER JOIN Treematching AS t
ON t.Name LIKE CONCAT('%',m.Name,'%')
Regarding the MySQL version, please have a look at the following link.
sqlfiddle

You might be able to do something like this (not tested, I don't have a sql-server instance):
SELECT M.Id, M.Name, T.Name
FROM matching AS M
INNER JOIN Treematching AS T
ON M.Name LIKE T.Name + '%';

Try the below query,
SELECT TM.ID,M.Name,TM.Name
FROM #matching AS M
INNER JOIN #Treematching AS TM ON TM.Name LIKE M.Name+'%'

SELECT A.ID,
B.NAME,
A.NAME AS TNAME
FROM TREEMATCHING A
INNER JOIN MATCHING B ON A.NAME LIKE B.NAME+'%'
ID NAME TNAME
----------- -------------------- --------------------
1 Child Child-Foster
2 Child Child-Filly
3 Child Child-Ricky
4 GrandChild GRandchild-Filmy
5 GrandChild GRandchild-Freaky
6 GrandChild GRandchild-Frim
9 parent parent-John

Related

Concat foreign key values from a self related table

I have a products database which has a multi-tier category structure. Products are assigned to a category. The category table looks like this:
id name parent_id
================================
1 Electronics NULL
2 AV 1
3 Speakers 2
4 Wireless 3
What I want to do is, as part of my SELECT statement for products, output a concatenated string of the category tree.
The product is always assigned to the last category, so for example, Product "500w Wireless Speakers" would be assigned to category_id 4 (based on the above).
The ouputted column should be Electronics-AV-Speakers-Wireless.
Is this possible to do? I have looked at GROUP_CONCAT() but I'm having trouble working out the correct syntax.
Join as many times as you need, and concat the names:
select concat(a.name, '-', b.name, '-', c.name, '-', d.name) name
from mytable a
join mytable b on a.id = b.parent_id
join mytable c on b.id = c.parent_id
join mytable d on c.id = d.parent_id;

SQL - Showing all parents from recursive relationship

I have a table for categories. This has a recursive relationship so that a category can become a subcategory of another category. The table looks like this:
id name short_desc long_desc tag_id parent_id
I wrote simple to get sql to find all level 1 categories:
SELECT * FROM category WHERE parent_id =0
Then I wrote a query to get all of the level 2 categories (where parent category doesn't have a parent)
SELECT * FROM category WHERE parent_id IN (SELECT id FROM category WHERE parent_id =0)
What I would like to do, is produce a column where is shows all category data and any relevant parent category.
Logically like this:
select all from category
if parent_id != 0, add the parent as a new row
repeat 2 until all parents have been accounted for.
The result should look something like this:
id name short_desc long_desc tag_id parent_name parent_name_2
if the parent_name is null / empty, then parent_name should remain empty. if there is a parent_name id in the field, then check to see if there is a parent_name_2 and if so, populate both columns, if not then only populate parent_name.
I do have the option of coding this in jquery or php which I have a good idea how to do. However, I am sure that I can get the data I need from a good SQL query.
Any help would be greatly appreciated.
Kind Regards
Nick
Here's one option using multiple outer joins:
select c.*,
case when c2.id is not null then c2.name end parent_name,
case when c3.id is not null then c3.name end parent_name_2
from category c
left join category c2 on c.parent_id = c2.id
left join category c3 on c2.parent_id = c3.id
SQL Fiddle Demo

Add columns when using IN in mysql for the result

Following is my table for artists -
id name sex
1 harsh male
2 geet female
Following is my table for events -
id artist_id created_by
2 2 16
2 2 17
Following is my query -
SELECT * FROM `events` WHERE artist_id IN (SELECT id FROM `artists` WHERE name LIKE '%$search_term%')
But apart from events data I need to get artist name in the result as well, please let me know what I need to change in my query as I tried *, artists.name it wont worked.
Try this query
SELECT e.*
FROM `artists` AS a
JOIN `events` AS e ON e.artist_id = a.id
WHERE a.name LIKE '%$search_term%';
You need to select from two tables simultaneously. Use the join for that
SELECT artists.name, events.*
FROM artists
INNER JOIN events
ON artist.id = artist_id
WHERE
name LIKE '%search_term%'
Use a join instead of an IN
SELECT
e.*,
artists.name
FROM
`events` e
inner join `artists` a on e.artist_id = a.id
WHERE
name LIKE '%$search_term%'

A Better way to optimize these MySQL queries

I have two MySQL tables:
attributes (attributeid, name)
productsattributes (productid, attributeid, displayvalue)
The required is for each attribute name called "Product Type" get all other attributes associated with this "Product Type". As an example — attributes table will look like:
attributeid name
1 A
2 B
3 Product Type
4 D
productsattributes table will look like:
productid attributeid displayvalue
1 3 FAN
1 1 Brown
1 2 Stand
2 3 FAN
2 4 D
3 3 CAR
3 4 imported
So the final result should be:
FAN (A,B, Product Type,D)
CAR (Product Type, imported)
Here is my try:
first I get all the "displayvalues" from productattributes:
SELECT DISTINCT displayvalue
FROM productsttributes
WHERE attributeid = 3;
then I loop through each "displayvalues" to find the other attributes:
SELECT a.name
FROM attributes a
INNER JOIN productsattributes pa
ON pa.attributeid = a.attributeid AND productid in (
SELECT productid
FROM productsttributes
WHERE dispalyvale = '$displayvalue')
ORDER BY a.name;
The problem is the productattributes table has about 7 million rows, so my script is taking forever .. of course I am not looking for 10 minutes solution but at least it will improve my queries a bit.
I would start with the following statements:
ALTER TABLE attributes ADD CONSTRAINT p_attributes PRIMARY KEY (attributeid);
ALTER TABLE productsattributes ADD CONSTRAINT p_productsattributes
PRIMARY KEY(productid, attributeid);
ANALYZE TABLE attributes, productsattributes;
This will make sure all important fields are indexed.
The query might look like this (also on SQL Fiddle):
SELECT trg.displayvalue,
group_concat(a.name ORDER BY trg.productid, a.attributeid)
FROM (
SELECT t.productid,t.displayvalue
FROM attributes a
JOIN productsattributes t USING (attributeid)
WHERE a.name = 'Product Type') AS trg
JOIN productsattributes p ON p.productid = trg.productid
JOIN attributes a ON a.attributeid = p.attributeid
GROUP BY trg.displayvalue
ORDER BY 1;
Please, kindly include the EXPLAIN output of your's and this queries into your question.
Try this ::
Select displayvalue, attribute_name
from
(Select
product_id from productsattributes pa inner join attributes_table at on (pa.attributeid=at.id) where at.name=?) as productList
inner join productsattributes pa2 on(pa2.product_id=productList.product_id)
inner join attributes_table at2 on (pa2.attributeid=at2.id)

getting child category's parent name with a single query in mysql

I have a mysql table named "category". the basic structure looks like this-
------ -------- ------
cat_id cat_name parent
------ -------- ------
1 test1 NULL
2 test2 NULL
3 test3 2
4 test4 1
5 test5 3
now i want all the category data with parent category name (not only id) in a single query. is that possible? i could do it by using a second query (getting child's parent name) in a while loop and merging data as a whole. but is it possible to do this with a single query?
Join the table with itself, using the parent column to link to the cat_id of the parent.
SELECT c1.cat_id as childID, c1.cat_name ChildName, c2.cat_name as ParentName
from category c1
LEFT OUTER JOIN category c2
ON c1.parent = c2.cat_id
Be careful: since some elements have no parents (NULL), I put a LEFT
OUTER JOIN so those rows are displayed as well. If you don't want
that, use a JOIN instead of LEFT OUTER JOIN.
You can also show the lines, but display something else (empty or a
text or ...) instead of the NULL by using COALESCE.
You can consider the result as one (big) new table, so you can add WHERE clauses as you usually do, for example filtering on the parent name: WHERE c2.cat_name = 'test2'
Select p.cat_id, p.cat_name, c.cat_id, c.cat_name, c.parent
From category Left Join category On p.cat_id = c.parent
Where p.cat_name = 'name'
SELECT c1.category_name AS category, c2. category_name AS sub_category
FROM (
SELECT *
FROM category
) AS c1
INNER JOIN (
SELECT *
FROM category
) AS c2 ON c1.category_id = c2.category_id