MySQL: Left join and column with the same name in different tables - mysql

Consider:
SELECT * FROM `product` left join category on product.category_id = category.id
This query works fine. But the problem is, both the product table and the category table have fields named "name" and "id". So when I fetch the result of this query, it gives me only one name and one id, but I want both id's and name's.
How can I do this without having to rename the fields?
Is it possible to return with custom names such as product_name and category_name?

You can add aliases to the fields:
SELECT
a.id,
a.name,
a.category_id,
b.id AS catId,
b.name AS catName
FROM
product AS a
LEFT JOIN
category AS b ON a.category_id = b.category.id

Use the "AS" keyword like:
SELECT product.id AS pid, category.id AS cid ... FROM `product` left join category on product.category_id = category.id

Use aliases with the AS keyword:
SELECT p.id AS product_id, p.name AS product_name, c.id AS cat_id, c.name AS cat_name
FROM `product` AS p
LEFT JOIN category AS c ON p.category_id = c.id

I had a similar problem working with MySQL in a Node.js project.
I found that if you still want to use select * instead of listing out all columns and using an alias, the following works:
SELECT *, category.id AS cId, category.name AS cName
FROM product LEFT JOIN category ON product.category_id = category.id
In other words, just create aliases for the joined columns that have conflicting names. You don't need aliases on other columns or on the table names.

SELECT p.*,c.* FROM product p LEFT JOIN category c on p.category_id = c.id;

Try this:
SELECT product.id AS productid,
category.id AS categoryid, ...
FROM `product` left join category
on product.category_id = category.id

No one has answered it so I am answering it.
If Table 1 has lots of columns like 20 columns and Table 2 has lots of columns like 20 columns. Then it is very tiresome to write a query like table1.a, table1.b
mysqli fetch assoc will return the columns of the right table if the column has same name. Easiest solution I found was to use table1.* in the select
SELECT table1.* FROM table1 LEFT JOIN table2 on table1.id=table2.id
WHERE table1.branch LIKE '%' and table2.branch LIKE 'City'
This will result in columns only from table1, left join and table2 columns were just for where clause.

Related

MySQL join on whichever column is not null

I have a table with a bunch of columns, but we only need to look at two of them. I'm trying to join another table on this table, but all we know about these two columns is that one will be null and the other won't:
client_id | note_id
The main table wants to join client_id (if not null) on clients.id OR note_id on notes.id if clients.id is null.
This will work for you. This is very basic query I wrote. Make changes if required.
SELECT * FROM YOUR_TABLE t
LEFT OUTER JOIN clients c ON t.client_id = c.id
LEFT OUTER JOIN notes n ON t.note_id = n.id
WHERE c.id IS NOT NULL OR n.id IS NOT NULL
Assuming there are 3 tables involved (the main table that contains client_id and note_id columns, clients table, and notes table), you can use a query such as this:
(select *
from mainTable inner join clients on mainTable.client_id = clients.id)
union
(select *
from mainTable inner join notes on mainTable.note_id = notes.id
where mainTable.client_id is NULL);
The above query contains 2 queries where each query will output rows where the joining column is not null. The results are then combined using union.
You can use coalesce in the join on clause. See demo here:
http://sqlfiddle.com/#!9/99911/2. If client id is null then use note id to join table1 and table2.
Select t1.client_id, t1.note_id,t2.client_id, t2.note_id
From table1 t1
Join table2 t2
on coalesce(t1.client_id, t1.note_id) =coalesce(t2.client_id, t2.note_id)

SQL - Duplicates in join

I have a query:
SELECT DISTINCT *
FROM table1 AS s
LEFT OUTER JOIN table2 AS t
ON s.s_id = t.t_id
WHERE (
s.body LIKE '%string%'
OR t.name LIKE '%string%'
)
ORDER BY s.time DESC
but I am still getting duplicate tuples. Why is this?
GROUP BY s.s_id
was the solution.
The result doesn't contain absolutely equal rows here so technically they aren't duplicated
To get rid of duplicates, you need to SELECT DISTINCT or GROUP BY only fields you need non-duplicated and outer join the rest data in subquery on the corresponding key values, taking only 1 (first or last or whatever) row from them.

How to count number of distinct values when joining multiple tables?

I have following database tables
categories
id, name
products
category_id, id, product_name, user_id
product_comments
product_id, id, comment_text, user_id
I need a count of number of different users in both products and product_comments tables. I have got the following query where I select all those categories where there is atleast one product and each product may have zero or some comments ... but what I can't figure out is that how to get the sum of these different user ids .. if it were just from one table I would try COUNT(products.user_id) ... .here is my query ..
SELECT
c.*
FROM categories c
INNER JOIN products p ON p.category_id = c.id
LEFT JOIN product_comments pc ON pc.product_id = p.id
I need total number of different users IDs from both products and product_comments tables.
I would expect the result data somewhat like below:
Category_id, Category_name, TotalUsers
1, Test Category, 10
2, Another Category, 5
3, Yet another cat, 3
This will give you an overall count rather than a list of all distinct id's:
SELECT COUNT(DISTINCT user_id)
FROM products
LEFT JOIN product_comments comm ON products.id = comm.product_id
If you want distinct users, then you could try something like:
select distinct user_id from (
select user_id from products
UNION
select user_id from product_comments
) as allusers;
You can then count them:
select count(distinct user_id) from (
select user_id from products
UNION
select user_id from product_comments
) as allusers;
select user_id from products
UNION
select user_id from product_comments
This will give you the distinct list of user ids that exist in the tables. The users could be present in just one of the tables, or both and will still be included in the list.
You can use the DISTINCT keyword and COUNT() function
SELECT DISTINCT
COUNT(c.*)
FROM categories c
INNER JOIN products p ON p.category_id = c.id
LEFT JOIN product_comments pc ON pc.product_id = p.id

sql sum for two tables

I need help with some basic sql...
here is the problem:
In first table I have
ID (primary key)
data column (varchar)
which contains products, in other I have
ID (primary)
second ID (foreign key) //references to ID from first table
price (decimal 8,2)
What I need is to SUM price from second table that corresponds products from first table. also it should be saved as view.
any help?
JOIN the two tables, with GROUP BY and an aggregate function SUM like this:
CREATE VIEW DataPrices
AS
SELECT
p.id,
p.data,
SUM(t.price)
FROM products p
INNER JOIN secondtable t ON p.ID = t.ForeignKeyToTable1
GROUP BY p.Id, p.data;
select table1.id, table1.data, sum(table2.price) as `total`
from table1 inner join table2
on table1.id = table2.foreignkeyId
group by table1.id, table1.data

Testing for the absence of child records in MySQL

I have two database tables with a one-to-many relationship. Is it possible to select records from the 'one' table for which no records exist in the 'many' table using a single SQL statement? If so, how?
Thanks in anticipation.
Use an OUTER JOIN:
select p.id
from parent p
left outer join child c on c.parent_id = p.id
where c.parent_id is null
select *
from table1
where not exists (select null
from table2
where MatchingColumn = Table1.MatchingColumn)
You can pull all the records from the master table that do not have any children in the "many" table like so:
SELECT T.*
FROM Table1 T
WHERE T.Id NOT IN(SELECT DISTINCT FKID FROM Table2)
FKID is the Foreign Key ID that links back to the master table.