Writing a SQL Query
I have two tables:
product_description( name , product_id)
product( quantity, stock_status_id, price, product_id)
What I am trying to do is run a query that will get me the above data but I am not sure how to implement a join to get the joined data from both tables.
Resolved
I did the following:
SELECT product_description.name, product.quantity,product.price
FROM product
开发者_如何学PythonINNER JOIN product_description
ON product.product_id=product_description.product_id
ORDER BY product_description.name
Operating under the assumption that you have matching product_id
s in each table, here's a query that will return the data you need using implicit joins:
SELECT product.product_id, name, quantity, stock_status_id, price
FROM product, product_description
WHERE product.product_id = product_description.product_id
UPDATE:
This works as I would expect. Here are two table dumps that might help you, and the output of the query.
product table:
--
-- Table structure for table `product`
--
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`product_id`, `name`) VALUES
(1, 'Croissant'),
(2, 'Danish');
product_description table:
--
-- Table structure for table `product_description`
--
CREATE TABLE IF NOT EXISTS `product_description` (
`product_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`stock_status_id` int(11) NOT NULL,
`price` double NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `product_description`
--
INSERT INTO `product_description` (`product_id`, `quantity`, `stock_status_id`, `price`) VALUES
(1, 6, 2, 12.5),
(2, 13, 1, 19.25);
Output from the above query:
"1","Croissant","6","2","12.5"
"2","Danish","13","1","19.25"
maybe something like this?
select p.id, p.quantity, p.stock_status_id, p.price, d.name
from Product p inner join `Product Description` d on d.product_id=p.id
although I'm still not sure of what the table schema actually looks like from the description in the question.
SELECT
-- name each column you want here
-- prefix columns from the PRODUCT table with its alias like so:
p.product_id,
-- prefix columns from the other table as its alias
d.quantity
FROM
PRODUCT p -- name of your PRODUCT table aliased as p
INNER JOIN -- join against your other table
PRODUCT_DESCRIPTION d -- name of your other table aliased as d
ON
p.product_id = d.product_id -- match the foreign keys
See INNER JOIN documentation for more details.
NOTE: This won't work as-is, you'll need to provide the columns that you want from each table in the SELECT
clause, and probably fix the table names to match for your application.
精彩评论