I have two tables in mysql, tender_items
and item_price_add_manual
.
Both the tables have fields called itemName
and tender_id
. So my requirement is how will i write a query to join these tables and show only certain itemNames
with eg:
tender_id
= 460. So the result in php comes like
tender_id | ItemName
______________________
460 Item 1
460 Item 2
460 Item 3
Is this possible with just a query or i need to manipulate with php script?
I TRIED THIS
SELECT tender_items.item_name,
tender_items.tender_id,
item_price_add_manual.item_name,
item_price_add_manual.tender_id
FROM tender_items INNER JOIN item_price_add_manual ON tender_items.tender_id=item_price_add_manual.tender_id WHERE tender_items.tender_id=460
With the above query iam getting the result as follows:
tender_id | ItemName | tender_id | ItemName
__________________________________________________
460 Item 1 460 Item 3
460 Item 2 460 Item 3
But i am expecting the result as follows:
tender_id | ItemName
______________________
460 Item 1
460 Item 2
460 Item 3
It seems like all you need is a UNION
operation:
(SELECT item_name, tender_id
FROM tender_items
WHERE tender_id=460)
UNION
(SELECT item_name, tender_id
FROM item_price_add_manual
WHERE tender_id=460)
As stated in the manual:
The default behavior for UNION is that duplicate rows are removed from the result.
Hence your requirement for distinct values selection will be satisfied as well.
SELECT item_name,tender_id FROM
((SELECT item_name, tender_id
FROM tender_items
WHERE tender_id=460)
UNION
(SELECT item_name, tender_id
FROM item_price_add_manual
WHERE tender_id=460)) AS T
GROUP BY item_name,tender_id
I presume that you have a foreign key which have linked the 2 tables together. You need not link everything from one table to another as it makes things very complex and erroneous may occur, making things hard to debug. You may look at W3School school tutorial to know how to SELECT
specifically.
$query = "SELECT * FROM tender_items, item_price_add_manual WHERE tender_items.tender_id = item_price_add_manual.tender_id AND tender_id = 460";