SQL Query joining two tables - mysql

I have 2 tables as below:
1.Products
product_id, name
1 Books A
2 Books B
3 Books C
4 Books D
5 Books E
2.liked_items
user_id, product_id
1 4
1 3
1 1
I want to query (sql) to retrieve result as below.
Can I do in same single query?
product_id, user_id
1 1
2 0
3 1
4 1
5 0
Hi, this first time i'm posting here.
Hope anyone can help me. Thank you

SELECT Products.product_id,liked_items.product_id,liked_items.user_id
FROM Products
LEFT JOIN liked_items
ON Products.product_id=liked_items.product_id

Try this one,
SELECT a.product_ID,
COALESCE(b.user_id,0) `user_id`
FROM products a
LEFT JOIN liked_items b
ON a.product_ID = b.product_ID
Sometimes liked_items.user_id can be possibly NULL so instead of displaying NULL in the result list, it can be changed using COALESCE. COALESCE is a function that can change NULL value into your desired value.
Click For Demonstration

SELECT
Products.product_id AS product_id,
IFNULL(liked_items.user_id,0) AS user_id
FROM Products
LEFT JOIN liked_items ON liked_items.product_id=Products.product_id

If you're using MS SQL Server you can use IsNull like so:
SELECT p.product_id, IsNull(li.user_id, 0)
FROM products p
LEFT JOIN liked_items li
ON (p.product_id = li.product_id);
If not, Joao or John's answer will do just fine.

Related

sql one-to-one relation with null values

I have two tables with one-to-one relations like: people has one to one relation with status table
**people table**
ID Name Status
1 Mick 1
2 Rohit null
3 Virat 1
4 Viru null
5 Gilly 2
6 Shann null
7 Mitch 3
**status table**
ID Status
1 started
2 not-started
3 pending
4 waiting
I need to get the people with status "null" and "started"(from ex: Mick, Rohit, Virat, Viru, Shann).
I tried with SQL query
select p.id, p.name
from people p
inner join status s on s.id = p.status
where (s.name IS NULL OR s.name = 'started')
this is giving only names which have a relation I mean "Mick, Virat" (skips nulls).
I don't know what I am missing here. thanks in advance
In order to keep people records where no status matches you need an OUTER join. In this case, a LEFT OUTER JOIN, which is often shortened to just LEFT JOIN:
select p.id, p.name
from people p
left join status s on s.id = p.status
where coalesce(s.name, 'started') = 'started'

SQL query to get results between 2 tables, and the second one has 3 possibilities of returning data

Even though my question was warned as similar title, I couldn't find here any similar problem. Let me explain in details:
I've got two tables (I'm working with MySQL) with these values inserted:
table products:
id name
1 TV
2 RADIO
3 COMPUTER
table sales (product_id is A FK which references products(id)):
id quantity product_id
1 50 2
2 100 3
3 200 3
The tv's haven't been sold, radios got 1 sale (of 50 unities) and computers got two sales (one of 100 e other of 200 unities);
Now I must create a query where I can show the products and its sales, but there are some conditions that make that task difficult:
1 - If there's no sales, show obviously NULL;
2 - If there's 1 sale, show that sale;
3 - If there's more than 1 sale, show the latest sale (which I've tried to use function MAX(id) to make it simple, and yet didn't worked);
In the tables example above, I expect to show this, after a proper SQL Query:
products.NAME sales.QUANTITY
TV NULL
RADIO 50
COMPUTER 200
I've been trying lots of joins, inner joins, etc., but couldn't find the result I expect. Which SQL query can give the answer I expect?
Any help will be very appreciated.
Thanks.
Hope the below query works.
SELECT products.name, sl.quantity
FROM products LEFT JOIN (
SELECT product_id, max(quantity) as quantity FROM sales GROUP BY product_id) sl
ON products.id = sl.product_id
In MySQL 8.0 you can do:
with m (product_id, max_id) as ( -- This is a CTE
select product_id, max(id) from sales group by product_id
)
select
p.name,
s.quantity
from products p
left join m on m.product_id = p.id
left join sales s on s.id = m.max_id
If you have an older MySQL, you can use a Table Expression:
select
p.name,
s.quantity
from products p
left join ( -- This is a table expression
select product_id, max(id) as max_id from sales group by product_id
) m on m.product_id = p.id
left join sales s on s.id = m.max_id

how to call subquery inside WHEN Clause - Mysql

i have two tables :
Product :
id name category
1 AAA BBB
2 CCC DDD
3 EEE FFF
Ordre:
id id_product date
1 2 10/11/16
2 2 06/16/16
3 3 12/09/16
4 1 02/06/16
5 3 15/10/16
in order to know if a product has an order i create this select query :
SELECT id,name ,category
CASE WHEN id IN (select id_product from Ordre) then 'Y'
ELSE 'N' END AS has_ordre
FROM product;
but this is not working for me, in the fact i want to create a View that contains the info about the products and also has the column "has_ordre" to check if a product has an ordre or not.
do you have any suggestion?
i'm new in Mysql
thanks in advance.
You can do what you need without a sub-query by doing a join on the two tables and a COUNT() on order.id_product, which will count the number of orders for each product. NOTE: this query will completely (as designed) exclude products which have no orders. Also, the result for this particular query will show the number of orders for each product:
SELECT p.id, p.name, p.category, COUNT(o.id_product) AS num_orders
FROM product p
RIGHT JOIN order o
ON p.id = o.id_product
GROUP BY p.id
ORDER BY num_orders
You can change the RIGHT JOIN to a LEFT JOIN if you would like to display all orders regardless of whether or not they have an active order:
Here is a fiddle

Mysql select unique value

I have a mysql table with the following structure:
id_category | id_product
1 1
15 1
28 1
5 2
15 2
1 2
13 3
4 3
I would like to make a query that I will use inside an "AND" clause of a JOIN structure which selects the products that have e.g. the id_category 1 and 15 and the output to be the id of the product but only once:
id_product
1
2
You may do as
select
id_product from table_name
where id_category in (1,15)
group by id_product
having count(*) = 2
You can use this:
select distinct(id_product) from TABLENAME
where id_category in (1,15)
You can use like this ;
select distinct(id_product) from table_name
where id_category=1 or id_category=15
group by id_product;
Here is SqlFiddle example
EDIT:
I understand what you mean.. I can give two example using join and where clause;
Lets look at first example;
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1'
As you see in the first example, character_id is filtering with where clause however, The where clause is filtering away rows where the left join doesn't succeed. So we need to do this in join with AND Move it to the join:
SELECT `settings`.*, `character_settings`.`value`
FROM `settings`
LEFT JOIN
`character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1'
So in order to use WHERE clause in join, use AND operator in JOIN. Hope this is helpful to solve your question.
EDIT2 :
In your problem it possible that you need to use OR not AND

Select rows with Left Outer Join and condition - MySQL

PEOPLE PEOPLE_FAVS
id user_id fav_id
------ ------- ----------
1 1 1
2 1 2
3 1 5
4 2 1
5 2 2
6
I have two tables PEOPLE and PEOPLE_FAVS, I am trying to get all PEOPLE which have not favorited number '5' so it should return
PEOPLE
id
------
2
3
4
5
6
I'm trying with this query:
SELECT `people`.`id`
FROM `people`
LEFT OUTER JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` != 5)
GROUP BY `people`.`id`
Here is a SQL Fiddle: http://sqlfiddle.com/#!2/4102b8/3
SELECT p.*
FROM people p
LEFT
JOIN people_favs pf
ON pf.user_id = p.id
AND pf.fav_id = 5
WHERE pf.fav_id IS NULL
http://sqlfiddle.com/#!2/665b6/1
You don't actually need to use an outer join. Outer joins are often used when you want to see ALL rows from one table, regardless of their condition with another. While it would work in this case (as seen by Strawberry's example), you can use the NOT EXISTS operator to check for ids that do not have 5 as a favorite.
As far as I am aware, there is little to no performance difference, but this query is a little shorter. I also feel it is a little more logical, because you aren't really joining information. That's just a personal opinion/thought though.
Try this:
SELECT id
FROM people
WHERE NOT EXISTS(SELECT id FROM people_favs WHERE fav_id = 5 AND user_id = id);
SQLFiddle example using your data.
Did you try to simply do this:
SELECT DISTINCT `people`.`id`
FROM `people`
JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` <> 5)
GROUP BY `people`.`id`