How to join 3 table and perform union in a subquery? - mysql

There are four table Bill_entry,Customer,Chit,Cash. I want to join table Customer with table Bill_entry in following query where they have common column customer_id. Goal here is by using customer_id i want to print customer_name too in one query.
i have tried but couldn't get correct syntax
Initial code before including Customer table :
SELECT Bill_entry.*
FROM (SELECT * FROM Chit UNION SELECT * FROM Cash) as t1 RIGHT JOIN
entry
ON (Bill_entry.bill_no = t1.bill_no)
WHERE t1.bill_no IS NULL
MY tries :
SELECT Bill_entry.*, Customer.customer_name
FROM ((SELECT * FROM Chit UNION SELECT * FROM Cash) as t1 RIGHT JOIN entry ON (Bill_entry.bill_no = t1.bill_no) WHERE t1.bill_no IS NULL)customer where Bill_entry.customer_id = Customer.Customer_id

Just add in another JOIN:
SELECT e.*, cu.customer_name
FROM bill_entry e LEFT JOIN
(SELECT * FROM Chit
UNION ALL -- assume you don't want to remove duplicates
SELECT * FROM Cash
) c
entry e
ON e.bill_no = c.bill_no LEFT JOIN
Customer cu
ON cu.customer_id = e.Customer_id
WHERE c.bill_no IS NULL;
Note some changes.
The UNION --> UNION ALL. I assume you don't want to remove duplicates or incur the overhead for trying to remove them.
RIGHT JOIN --> LEFT JOIN. It is usually much simpler to think about LEFT JOINs -- keep all the rows in the first table and then matching rows in the others.
The JOIN conditions are all in ON clauses, not the WHERE clause.

Related

MySQL SELECT in SELECT-clause or in WHERE-clause in order to filter further

I'm trying to filter some data, but as the data comes from 2 tables in the database I have to union them together, permitting nulls from the second table as I always need to have any values available in the first table, due to this being a product database with some products having sub-combinations and some none. Thus far I've come up with using a Union to join the two tables together, but now I need a method to filter out the data using a WHERE clause; however: this is where I get stuck. I tried putting the union as a select statement in the FROM clause: no data returned, I tried to put it into the SELECT clause as a sub: no data returned...
In short I need something like this:
SELECT id_product, id_product_attribute,upc1,upc2
FROM (UNION)
WHERE upc1='xyz' OR upc2='xyz';
where for example the result might be things such as:
-> 100, null, 9912456, null
or
-> 200, 153, 9915559, 9977123
Currently I have this (sorry I don't have more):
(SELECT product.id_product as id_product,
product.upc as upc1,
comb.id_product_attribute,
comb.upc as upc2
FROM `db`.table1 product
LEFT JOIN `db`.table2 comb
ON comb.id_product = product.id_product
)
UNION
(SELECT product.id_product as id_product,
product.upc as headCNK,
comb.id_product_attribute,
comb.upc
FROM `db`.table1 product
RIGHT JOIN `db`.table2 comb
ON comb.id_product = product.id_product
);
Also note that upc1 is coming from table 1, and upc2 from table2.
I could use the entire query, and filter out everything using some business logic in the worst case scenario, but rather not as I don't want to perform endless queries where I don't have to, my service provider doesn't like that...
UPDATE:
I also tried:
SELECT *
from db.t1 as prod
CROSS JOIN db.t2 as comb ON prod.id_product = comb.id_product
WHERE prod.upc = 'xyz' OR comb.upc = 'xyz';
This didn't work either.
Placed a fiddle here with some small sample data:
http://sqlfiddle.com/#!9/340d7d
The output for the '991002' used in the where clause in query SELECT id_product, id_product_attribute, table1.upc, table2.upc should be: 101, null, 991002, null
And for '990001' it should then be: 101, 201, 990001, 990001
For all values try
SELECT t1.id_product, t2.id_product_attribute, t1.upc, t2.upc
FROM ( SELECT upc FROM table1
UNION
SELECT upc FROM table2 ) t0
LEFT JOIN table1 t1 USING (upc)
LEFT JOIN table2 t2 USING (upc)
For definite upc value edit to
...
SELECT t1.id_product, t2.id_product_attribute, t1.upc, t2.upc
FROM ( SELECT 990001 upc ) t0
LEFT JOIN table1 t1 USING (upc)
LEFT JOIN table2 t2 USING (upc)
...

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)

mysql count records by subquery on same table

my problem is that i am joining 4 tables by left join so i cant use group by rather than sub query.
but how do i get the count of main table based on specific column
any tips .
Is it possible.
Thanks in advance
I have tried this way.
SELECT * ,sql_1.trans
FROM table1 a
LEFT JOIN table b ON condition
LEFT JOIN ( SELECT count(*) trans,dentist_id as did3 FROM table1
GROUP BY dentist_id
) sql_1 ON did3=a.dentist_id
WHERE a.current_tab='pack'

mysql query result issue with join

I have multiple tables as table_1 has id , p_code, profile_status, name and table_2 has id, p_code, availablity and table_3 has id, p_code, status...
How to get all records form all tables depend on p_code.
table_2 and table_3 has few records. if p_code not in table_2 and table_3 then echo 'no' in results.
currently i am using my query as below
select t.id, t.p_code,t.name,t.num_rooms, t.profile_status, t.distance FROM (
( SELECT id , p_code, profile_status, name,num_rooms, 3956 * 2 * ASIN(SQRT( POWER(SIN(($origLatAirport - latitude)*pi()/180/2),2)
+COS($origLatAirport*pi()/180 )*COS(latitude*pi()/180)
*POWER(SIN(($origLonAirport-longitude)*pi()/180/2),2)))
as distance FROM property WHERE profile_status=1 having distance < ".$dist." ) ) as t
How to add table_2 and table_3 and fetch results.
Pleasr reply soon. I am stuck here.
In your query you are doing CROSS JOIN and what you desire, is probably INNER JOIN.
In MySQL the CROSS JOIN behaves like JOIN and INNER JOIN of without using any condition.
The CROSS JOIN returns all rows form user multiplied by all rows from user_inbox - for every user you get inboxes of all users.
You should specify condition for your JOIN statement.
$sql_alt = mysql_query(
"select i.*,u.images, u.firstname, u.lastname
from user_inbox i INNER JOIN user u ON i.to_id = u.user_id
where i.to_id = '$user_id'");
Also it is good habit have the same names for primary and foreign keys, so I think you should have user_id or user_id_to instead of to_id in your user_inbox table. This is of course not absolutely necessary.

MySQL, merging 2 or more tables before execute SELECT DISTINCT query?

I want to calculate how many unique logins from 2 (or probably more tables).
I tried this:
SELECT count(distinct(l1.user_id))
FROM `log_1` l1
LEFT JOIN `log_2` l2
ON l1.userid = l2.userid;
But it gives me result of l1. If I didn't put l1 on li.userid (distinct), it said "ambiguous".
How do I combine the table, and then select unique login of the combined table?
EDIT:
Tested: I test the count(distinct(l1.userid)) and count(distinct(l2.userid)). It gives me different result
If you are using LEFT JOIN then you will get at least one row in the combined result for each row in l1, so the join is entirely unnecessary if you just want a distinct count. This would give you the same result as your query:
SELECT count(distinct(l1.user_id))
FROM `log_1` l1
Perhaps you want an INNER JOIN or UNION instead? A UNION will count a user if they appear in either table. An INNER JOIN will count them only if they appear in both tables. Here's an example of the UNION:
SELECT count(*) FROM (
SELECT distinct(user_id) FROM `log_1`
UNION
SELECT distinct(user_id) FROM `log_2`
) T1