How to properly join tables with a many to one relationship - php

I have six tables
The main table Orders is an encrypted table containing orders that customers have made.
The second table is a hash table for the Orders table. OrdersHash.
The remaining four tables are store tables that all have the same structure. StoreA, StoreB, StoreC, & StoreD.
Orders Table
orderId | rest of row...
OrdersHash Table
orderId | orderIdHash | rest of row..
The four store tables all share this structure.
orderIdHash | customerId | rest of row..
Using only the customerId I am trying to query the four store tables to see if any of the store tables contain the customerId. If the customerId is found on any of the four store tables I want to use the orderIdHash to get me back to the original Orders table and return the row for any orders that were found.
If I use a the customerId for Mike I would expect row 1 from the Orders table.
This is what I have tried so far.
"SELECT
o.dateShipped AS orderShipped,
o.shipped AS shipped,
o.recieved AS recieved
FROM Orders o
JOIN OrdersHash oHash
ON o.orderId = oHash.orderId
JOIN StoreA a
ON ohash.orderIdHash = a.orderIdHash
JOIN StoreB b
ON ohash.orderIdHash = b.orderIdHash
JOIN StoreC c
ON ohash.orderIdHash = c.orderIdHash
JOIN StoreD d
ON ohash.orderIdHash = d.orderIdHash
WHERE
a.customerId = :customerId1
OR b.customerId = :customerId2
OR c.customerId = :customerId3
OR d.customerId = :customerId4";
**customerId 1,2,3,4 are all the same value.. I have to use a different name for binding in PDO.
This will return a result but it seems to return the same row from Orders for every row in a store with a matching orderIdHash when I just need the one record from the Orders table.
Thank you in advance for your help.

It seems you probably want to UNION the store results and then JOIN that to the Orders table. By using UNION rather than UNION ALL, we can select only the distinct orderIdHash values, ensuring we only get one row for each Order in the result table. Something like this:
SELECT o.dateShipped AS orderShipped,
o.shipped AS shipped,
o.recieved AS recieved
FROM (SELECT customerId, orderIdHash
FROM (SELECT customerId, orderIdHash FROM StoreA
UNION
SELECT customerId, orderIdHash FROM StoreB
UNION
SELECT customerId, orderIdHash FROM StoreC
UNION
SELECT customerId, orderIdHash FROM StoreD
) stores
WHERE customerId = :customerId) c
JOIN OrdersHash oHash ON oHash.orderIdHash = c.orderIdHash
JOIN Orders o ON o.orderId = oHash.orderId

Related

Counting values from two tables and returning the result in a single value

How to count value from two tables and return the result in a single value.?
I had two tables named order and affiliate, like below:
order:
order_ID(primary key), order_name, Order_status, affiliate_ID (foreign key)
affiliate:
affiliate_ID (primary key),affiliate_name
Now, I want to count the orders based on affiliate name by comparing the affiliate_ID on order table and affiliate table.
I have tried it like this:
Query
SELECT COUNT(*)
FROM order o
AND (SELECT COUNT (affiliate_name) FROM affiliate a
WHERE a.affiliate_id = O.affilate_id) AS total
It returns an error.
I feel this is what you need
SELECT a.affiliate_ID, a.affiliate_name, COUNT(o.order_ID) as total
FROM order o
LEFT JOIN affiliate a ON o.affiliate_ID = a.affiliate_ID
GROUP BY o.affiliate_ID;
to add WHERE clause, see sample
SELECT a.affiliate_ID, a.affiliate_name, COUNT(o.order_ID) as total
FROM order o
LEFT JOIN affiliate a ON o.affiliate_ID = a.affiliate_ID
WHERE o.affiliate_ID = 3
GROUP BY o.affiliate_ID;
Not sure I understand your question correctly, but is this what you're looking for ?
SELECT *, COUNT(*) as total
FROM order o
JOIN affiliate a ON a.affiliate_id = o.affiliate_id
GROUP BY o.affiliate_id
Otherwise, provive sample & desired result example please.

PHP Join Query for Three Table When There is No Direct Common Column?

I have Three Tables in which first two tables have common column to match the record, and 2nd and third table also have common column but there is no direct matching column in first and third table. How shall I write join query ?
Table1(order) Column Names are order_id, patient_id, total, discount
Table2 (order_details) Column Names are order_details_id, order_id, test_id, result
Table3(tests) Column Names are test_id, test_name, test_normal_value
I hope it helps
SELECT * FROM `order`
LEFT JOIN `order_details` ON `order`.`order_id` = `order_details`.`order_id`
LEFT JOIN `tests` ON `order_details`.`test_id` = `test`.`test_id`
"SELECT a.patient_id FROM table1 as a
LEFT JOIN table2 as b on a.order_id = b.order_id
LEFT JOIN table3 as c on c.test_id = b.test_id";
to join this 3 table in one query, we need to assign each table a name. For example table1 AS NewNameTable1 LEFT JOIN table2 AS NewNameTable2. To connecting between this 3 table we need to have a foreign key for each table. So that this 3 table able to JOIN and we able to fetch the data in single query. As long this 3 table is JOINED via foreign key, you can echo out any attribute from any table that Joined.

Join 3rd table inside the WHERE clause

I'm trying to extend a 2 table join query to join 3 tables. I'm using PDO
SELECT tb.product, COUNT(tb.ID) AS nums FROM items tb LEFT JOIN itemCode cod ON tb.ID = cod.codeID WHERE tb.product = :product AND cod.name = :cName
The above 2 table join works. My question is, how do I match itemCode's availabilityID column to tblC's stockID column and add it to the WHERE clause with same query to get the result?
So basically I want to check if the availabilityID column of itemCode table match with stockID column of tblC table.
EDIT: table structure:
**items table**
ID | product
**itemCode table**
codeID | name
**tblC table**
stockID
As stated in your question you want to match availabilityID with stockID, this is what the query does. However, the availabilityID does not show up in your edit.
SELECT tb.product, COUNT(tb.ID) AS nums
FROM items tb
LEFT JOIN itemCode cod ON tb.ID = cod.codeID
JOIN tblC stock ON stock.`stockID` = cod.`availabilityID`
WHERE tb.product = :product AND cod.name = :cName

multiple joins for different ids in same and different tables

I've different tables and I've to fetch data.
order table
orderId, clientId, buyerId, loadingCompanyId, productTypeId, orderStatusId
user table
userId, userCompanyName
orderStatus table
orderStatusId, orderStatusName,
productType table
productTypeId, productTypeName
so I've these tables. In order table clientId, buyerId and loadingCompanyId are coming from user's table userId and I want to fetch its userCompanyName, orderStatusId is coming from orderStatus table and I want to fetch orderStatusName and last one is productTypeName productTypeId is coming from productType table and want to fetch productTypeName but the problem is with clientId, buyerId and loadingCompanyId these three ids are userId from user table so how I've to fetch client, buyer and loading company names.
That are some simple joins with aliases
select *
from order
join user client on clientId = client.userId
join user buyer on buyerId = buyer.userId
join user company on loadingCompanyId = company.userId
join orderStatus on orderStatus.orderStatusId= order.orderStatusId
join productType on productType.productTypeId = order.productTypeId
SELECT O.orderId, UserClient.userCompanyName As clientName, UserBuyer.userCompanyName AS buyerName, UserloadingCompany.userCompanyName AS buyerName, OS.orderStatusName, PT.productTypeName
FROM Order O
INNER JOIN user AS UserClient
ON O.clientId = UserClient.userId
INNER JOIN user AS UserBuyer
ON O.buyerId = UserBuyer.userId
INNER JOIN user AS UserloadingCompany
ON O.loadingCompanyId = UserloadingCompany.userId
INNER JOIN orderStatus AS OS
ON O.orderStatusId = OS.orderStatusId
INNER JOIN productType AS PT
ON O.productTypeId = PT.productTypeId

Need the highest ID using left join

I have two tables,
TABLE 1 has many of each client and campaign and is very large
TABLE 2 has only one of each client and campaign and is small.
So I want to get the lastest(highest ID) from TABLE 1 where it matches the client and campaign in TABLE 2 and only one of each.
I have tried MAX, and playing with the order by etc, but cant get it working....
The results I get are choosing the lowest ID from TABLE 1 (I want highest)
$result2 = mysql_query("SELECT table1.client,table1.campaign,table1.id
FROM table1
LEFT OUTER JOIN
table2
ON (table2.client = table1.client)
AND (table2.campaign = table1.campaign )
WHERE (table2.enabled != 'disabled')
group by campaign asc
order by client,campaign,id asc
");
Help needed....
SELECT * FROM table1
INNER JOIN
(
SELECT MAX(table1.id) AS id FROM table1
INNER JOIN table2 ON table2.client = table1.client AND table2.campaign=table1.campaign and table2.enabled != 'disabled'
GROUP BY table1.client, table1.campaign
) AS m ON m.id = table1.id
I think that's what you're asking for. For each combination of client and campaign that exists in each table, it will give you the highest ID in table 1.

Categories