SQL query on multiple tables - mysql

Suppose i have the following 2 tables:
Persons Table:
Name
ID[Primary Key]
Fruits Table:
Name
ID[Foreign Key Persons.ID]
This is a table structure for storing persons and the fruits they like. Now if I want to find all the persons who like "Apple" and "Orange"(this would be dynamic). How can i design a SQL query for that?

You can use a query like the following to get the IDs of all persons who like Apples and Oranges:
SELECT p.ID
FROM Persons AS p
JOIN Fruits AS f ON p.ID = f.PersonsID
WHERE f.Name IN ('Apple', 'Orange')
GROUP BY p.ID
HAVING COUNT(DISTINCT f.Name) = 2

Related

SQL Join 3 Tables and concatenate values

I have 3 Tables with a n:m Relation
Languages:
ID (primary-key)
name
slug
Products:
ID
name
slug
-productgroup
Table for Relation:
Lang_Prod:
lang_prod_id (composed from lang_id and prod_id)
lang_id
prod_id
Now i want to get all Products with their corresponding Language-Names:
product
productgroup
language-names (multiple values)
I've tried:
SELECT product.*, languages_products.language_id,
GROUP_CONCAT(languages_products.language_id) as languages
FROM product
INNER JOIN languages_products ON id = languages_products.product_id
GROUP BY product.id;
Result is:
productname
product_slug
product_group
String with languages IDs
Instead of the string with the language-IDs, i would like to have a string with language-names
How can i archieve that?
You need to join with language table
SELECT product.id,product.name,product.productgroup,
GROUP_CONCAT(l.name) as languages
FROM product
INNER JOIN languages_products ON id = languages_products.product_id
INNER JOIN languages l ON languages_products.language_id=l.id
GROUP BY product.id,product.name,product.productgroup
You need to add another join with the languages table, and use the name column from it. I'd group it in an inner query though:
SELECT p.*, languages
FROM product p
JOIN (SELECT product_id, GROUP_CONCAT(l.name) as languages
FROM languages_products lp
JOIN languages l ON lp.language_id = l.id
GROUP BY product_id) cl ON cl.product_id = p.id

How to get Data from three tables in one query where table 2 contains foreign keys from table 1 and 3

I want to get all the suppliers for one product with product details for which I am using following tables.
I have one Table products with columns
id(pk)
name
type
second table product_supplier with columns
psid(pk)
pid(fk from products)
sid(fk from supplier)
third table supplier with columns
id(pk)
firstname
lastname
I want to get data from these three tables in one mysql query.
Is this what you are looking for?
select p.*, s.*
from products p
inner join product_supplier ps on ps.pid = p.id
inner join supplier s on s.id = ps.sid
order by p.id, s.id
This will return each product along with all the associated suppliers.

SQL - Counting how many associated records another table has

As I'm SQL beginner, I can't describe a problem in a simple way, so let me show you an example:
3 Tables:
PRODUCT
id
group_id
person_id
GROUP
id
name
PERSON
id
group_id
As you see, GROUP can have multiple PERSONs and PRODUCT can be connected with GROUP and PERSON.
From this point, I would like to count number of PERSONs having a PRODUCT within a GROUP
I don't really understand the background of IN or using another SELECT within FROM, so if that's the point, then I'm happy that I was one step before it lol.
SELECT
group.name as GROUP_name,
COUNT(DISTINCT person_id) AS PERSON_having_min_one_PRODUCT
FROM products
LEFT JOIN groups ON groups.id = products.group_id
LEFT JOIN persons ON persons.id = products.person_id;
With this data:
GROUP
ExampleGroupName1 has 3 PERSONs, but 2 of them has >0 PRODUCTS
ExampleGroupName2 has 3 PERSONs and all of them has >0 PRODUCTS
ExampleGroupName3 has 2 PERSONs, but none of them has the PRODUCT
ExampleGroupName4 has 2 PERSONs, but only 1 has >0 PRODUCT
I would like to have an output like this:
GROUP_name | PERSON_having_min_one_PRODUCT
ExampleGroupName1 | 2
ExampleGroupName2 | 3
ExampleGroupName4 | 1
I would like to count number of PERSONs having a PRODUCT within a GROUP
Note: I will assume the table product does not have the column group_id, since it is redundant and can lead to a lot of errors.
The following query will show you the result you want by joining the tables person and product:
select
count(distinct x.id)
from person x
join product p on p.person_id = x.id
where x.group_id = 123 -- choosing a specific group
and p.id = 456 -- choosing a specific product
This would rather be simple like below meaning all the groups with some group_id with count(persons) and those count who has some product via id used in having clause
Select group_id,
count( distinct id ) AS "PERSON_WITH_PRODUCT"
from
person group by group_id having id
in (Select id from product);

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;

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)